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 n
 array (e.g., if the total number of elements in theÂoriginal
 is not equal toÂm * 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
original
must equalÂm
Ă—n
, whereÂm
 is the number of rows andÂn
 is 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
, withÂm
 rows andÂn
 columns. Each cell in this array is initialized with0 .
We initialize a variable,
index
, with0 to keep track of the current position in theÂoriginal
 array.We iterate over each row, using
i
, and each column usingj
of 2D arrayresult
.While iterating, for each position (
i
,j
)Â in the 2D array, the corresponding element from theÂoriginal
 (tracked by theÂindex
) is assigned to the 2D array (result[i][j] = original[index]
).After assigning, theÂ
index
 is incremented to move to the next element in theÂoriginal
.
Once all elements(
m
xn
) are assigned, the populated 2D arrayresult
is returned as the output.
Let’s look at the following illustration to get a better understanding of the solution: