Problem Description
Given a 1D integer array named original and two integers m and n, construct a 2D array with m rows and n columns using all the elements from original. The first n elements form the first row, the next n elements form the second row, and so on. If the number of elements in original does not equal m * n, return an empty 2D array.
Key Insights
- Ensure the total number of elements in original is exactly m * n; otherwise, constructing the desired 2D array is impossible.
- Use slicing or index arithmetic to break original into chunks of n elements.
- The simulation approach works by iteratively creating each row from the original array.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n)
Solution
The solution checks whether the length of original matches m * n. If not, it immediately returns an empty 2D array. If the size requirement is met, iterate over the original array and slice it into segments of length n to form each row of the 2D array. This method leverages array slicing (or index arithmetic) to organize the elements correctly and build the required matrix.