Convert 1D Array Into 2D Array — Problem & Solution
Convert 1D Array Into 2D Array solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Convert 1D Array Into 2D Array is an easy coding problem on arrays, matrix and simulation, asked in Amazon and Microsoft interviews.
- Difficulty: Easy
- Topics: Arrays, Matrix, Simulation
- Asked at: Amazon, Microsoft
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a 1-D array original and two integers m and n. Build a 2-D array of m rows and n columns using all the elements of original, in order: the first n elements form the first row, the next n the second row, and so on.
If that is impossible, return an empty 2-D array.
Example 1
Input: original = [1,2,3,4], m = 2, n = 2
Output: [[1,2],[3,4]]
Example 2
Input: original = [1,2,3], m = 1, n = 3
Output: [[1,2,3]]
Example 3
Input: original = [1,2], m = 1, n = 1
Output: []
Explanation: Two elements cannot fill a 1 × 1 grid.
Constraints
1 <= original.length <= 401 <= original[i] <= 1000001 <= m, n <= 40
Hints for Convert 1D Array Into 2D Array
Hint 1
The build is possible exactly when
original.length == m * n.Hint 2
Then row
ris the slice fromr * ntor * n + n.
How to solve Convert 1D Array Into 2D Array
Possible only when len == m · n; then row r is the slice original[r·n : r·n + n].
Approach
- Return
[]if the lengths disagree. - Slice the array into
mrows ofn.
Why it works
Row-major filling maps flat index k to (k // n, k % n), which is exactly what consecutive slices of length n produce.
Complexity
- Time —
O(m · n) - Space —
O(m · n)
Pitfalls
- Return an empty 2-D array, not
null, on mismatch.
Reference solution
Python
def construct2DArray(original, m: int, n: int):
if len(original) != m * n:
return []
return [original[r * n:(r + 1) * n] for r in range(m)]Java
public static int[][] construct2DArray(int[] original, int m, int n) {
if (original.length != m * n) return new int[0][];
int[][] out = new int[m][n];
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) out[r][c] = original[r * n + c];
}
return out;
}C++
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if ((int) original.size() != m * n) return {};
vector<vector<int>> out(m, vector<int>(n, 0));
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) out[r][c] = original[r * n + c];
}
return out;
}JavaScript
var construct2DArray = function(original, m, n) {
if (original.length !== m * n) return [];
const out = [];
for (let r = 0; r < m; r++) out.push(original.slice(r * n, r * n + n));
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Matrix and Grid Traversal