Solution: Convert 1D Array Into 2D Array
Let’s solve the Convert 1D Array Into 2D Array problem using the Matrices pattern.
We'll cover the following
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 theoriginal
is not equal tom * n
), return an empty 2D array.
Constraints:
original.length
original[i]
m
,n
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 equalm
×n
, wherem
is the number of rows andn
is the number of columns.If
m
n
, reshaping is not possible, and we immediately return an empty 2D array. Otherwise, we initialize a 2D array,
result
, withm
rows andn
columns. Each cell in this array is initialized with.
We initialize a variable,
index
, withto 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 theoriginal
(tracked by theindex
) is assigned to the 2D array (result[i][j] = original[index]
).After assigning, the
index
is incremented to move to the next element in theoriginal
.
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:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.