Solution: Convert 1D Array Into 2D Array
Explore how to convert a one-dimensional integer array into a two-dimensional array with specified rows and columns by preserving element order. Understand the conditions for valid transformation and implement the iterative method to fill the 2D array efficiently using Python. This lesson helps build foundational skills in array reshaping and matrix operations useful for coding interviews.
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 narray (e.g., if the total number of elements in theoriginalis not equal tom * n), return an empty array.
Constraints: ...