Convert 1D Array Into 2D Array
Problem
Given a 0-indexed 1D integer array original and two integers m and n, build an m × n 2D array using all of original's elements. Indices 0..n−1 form row 0, indices n..2n−1 form row 1, and so on. Return the constructed 2D array, or an empty array if it is impossible (when the element count does not equal m × n).
original = [1,2,3,4], m = 2, n = 2[[1,2],[3,4]]original = [1,2], m = 1, n = 1[]def construct_2d_array(original, m, n):
if len(original) != m * n:
return []
result = [[0] * n for _ in range(m)]
for i in range(len(original)):
r = i // n
c = i % n
result[r][c] = original[i]
return result
function construct2DArray(original, m, n) {
if (original.length !== m * n) {
return [];
}
const result = Array.from({ length: m }, () => new Array(n).fill(0));
for (let i = 0; i < original.length; i++) {
const r = Math.floor(i / n);
const c = i % n;
result[r][c] = original[i];
}
return result;
}
int[][] construct2DArray(int[] original, int m, int n) {
if (original.length != m * n) {
return new int[0][0];
}
int[][] result = new int[m][n];
for (int i = 0; i < original.length; i++) {
int r = i / n;
int c = i % n;
result[r][c] = original[i];
}
return result;
}
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if ((int)original.size() != m * n) {
return {};
}
vector<vector<int>> result(m, vector<int>(n));
for (int i = 0; i < (int)original.size(); i++) {
int r = i / n;
int c = i % n;
result[r][c] = original[i];
}
return result;
}
Explanation
The only thing that can make this impossible is a size mismatch: an m × n grid holds exactly m · n cells, so if original has a different number of elements there is no valid reshape and we return an empty array immediately.
When the sizes match, we walk through original once with a flat index i. The key insight is that each flat index maps to a grid cell by simple integer arithmetic: the row is i // n (how many full rows of width n came before) and the column is i % n (the offset within the current row).
We place original[i] into result[i // n][i % n]. As i sweeps from 0 upward, the column cycles 0, 1, …, n−1 and resets while the row advances by one — exactly filling the grid left to right, top to bottom.
Because each element is read and written once, the work is linear in the number of elements, O(m · n), and the output array itself is the only extra space.
Example: original = [1,2,3,4,5,6], m = 2, n = 3. Indices 0,1,2 land in row 0 as [1,2,3] and indices 3,4,5 land in row 1 as [4,5,6].