Solution: Convert 1D Array Into 2D Array

Let’s solve the Convert 1D Array Into 2D Array problem using the Matrices pattern.

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<=1 <= original.length <=103<= 10^3

  • 1<=1 <= original[i] <=103<= 10^3

  • 1<=1 <= m, n <=33<= 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:

  1. 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.

    1. If m ×× n len(original)\neq \text{len(original)}, reshaping is not possible, and we immediately return an empty 2D array.

    2. Otherwise, we initialize a 2D array, result, with m rows and n columns. Each cell in this array is initialized with 00.

  2. We initialize a variable, index, with 00 to keep track of the current position in the original array.

  3. We iterate over each row, using i, and each column using j of 2D array result.

    1. 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]).

    2. After assigning, the index is incremented to move to the next element in the original.

  4. Once all elements(m x n) are assigned, the populated 2D array result 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.