Statement▼
Given a 0-indexed 1-dimensional (1D) integer array original and two integers, m and n, your task is to reshape the array into a 2-dimensional (2D) array with m rows and n columns while preserving the order of elements in original.
To construct the 2D array, the first n elements in the original should populate the first row. The next n elements should populate the second row, and so on, until all rows are filled. Your goal is to return the resulting m x n 2D array.
Note: If it is impossible to create an
m x narray (e.g., if the total number of elements in theoriginalis not equal tom * n), return an empty 2D array.
Constraints:
1<= original.length<=103 1<= original[i]<=103 1<= m,n<=33
Solution
The essence of this solution lies in reshaping the given 1D array into a 2D array of specified dimensions while ensuring possibility based on the input constraints. The solution verifies if the reshaping is possible by comparing the total elements in the 1D array with the required m x n elements of the 2D array. If valid, it initializes a 2D array and fills it with elements from the original array while maintaining their order.
Now, let’s look at the steps of the solution:
We first verify whether the reshaping is possible by checking that the number of elements in the
originalmust equalm×n, wheremis the number of rows andnis the number of columns.If
m× n=len(original) , reshaping is not possible, and we immediately return an empty 2D array.Otherwise, we initialize a 2D array,
result, withmrows andncolumns. Each cell in this array is initialized with0 .
We initialize a variable,
index, with0 to keep track of the current position in theoriginalarray.We iterate over each row, using
i, and each column usingjof 2D arrayresult.While iterating, for each position (
i,j) in the 2D array, the corresponding element from theoriginal(tracked by theindex) is assigned to the 2D array (result[i][j] = original[index]).After assigning, the
indexis incremented to move to the next element in theoriginal.
Once all elements(
mxn) are assigned, the populated 2D arrayresultis returned as the output.
Let’s look at the following illustration to get a better understanding of the solution: