Convert 1D Array Into 2D Array (LeetCode 2022): Solution and Explanation
Given an array original and a target shape m x n, lay the values out row by row into an m x n grid. If the array has more or fewer than m * n values, return an empty 2D array.
Intuition
Think of original as a paper tape. An m x n grid read row by row is just that tape cut into m pieces of length n and stacked.
The only thing that can go wrong is the length. If the tape is shorter than m * n, some grid cells stay empty; if it is longer, values are left over. Both cases have no valid answer.
Once the length matches, row i is simply the slice from index i * n up to (i + 1) * n. No searching or rearranging is involved.
Approach: Size check, then slice every n values
- If
m * n != len(original), return[]. - Create an empty result list.
- For each
ifrom0tom - 1, appendoriginal[i * n:(i + 1) * n]. - Return the result.
Step-by-step example
original = [1,2,3,4], m = 2, n = 2
- m * n = 4, which equals the length of original, so a 2 x 2 grid is possible.
- i = 0: cut indexes 0..1, giving row [1,2].
- i = 1: cut indexes 2..3, giving row [3,4].
- The result is [[1,2],[3,4]].
Code: Python, Java, C++
1class Solution:
2 def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
3 if m * n != len(original):
4 return []
5 res = []
6 for i in range(m):
7 res.append(original[i * n:(i + 1) * n])
8 return res1class Solution {
2 public int[][] construct2DArray(int[] original, int m, int n) {
3 if (m * n != original.length) {
4 return new int[0][0];
5 }
6 int[][] res = new int[m][n];
7 for (int i = 0; i < m; i++) {
8 System.arraycopy(original, i * n, res[i], 0, n);
9 }
10 return res;
11 }
12}1class Solution {
2public:
3 vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
4 if ((long long)m * n != (long long)original.size()) {
5 return {};
6 }
7 vector<vector<int>> res(m);
8 for (int i = 0; i < m; i++) {
9 res[i] = vector<int>(original.begin() + i * n, original.begin() + (i + 1) * n);
10 }
11 return res;
12 }
13};Time and space complexity
O(m * n)
Every value is copied into the grid exactly once; the size check is O(1).
O(m * n)
The returned grid holds all m * n values. Nothing else grows with the input.
Other approaches
Index arithmetic per value (time O(m * n), space O(m * n))
Allocate an m x n grid and walk k over original, writing original[k] to grid[k // n][k % n]. Same cost, useful when the language has no cheap slice.
Two cursors (time O(m * n), space O(m * n))
Keep a row and a column cursor, advance the column for every value and wrap to the next row when it reaches n. Equivalent work with more bookkeeping.
Common mistakes
- Skipping the size check: slicing past the end silently produces short rows in Python and JavaScript instead of failing.
- Allocating the
m x ngrid before checking the size. With m and n up to 40,000 that is 1.6 billion cells for an input that should return[]. - Using
nandmthe wrong way round: each row hasnvalues and there aremrows. - In C++ or Java,
m * nfits in a 32-bit int under these constraints, but casting to a wider type is a cheap guard if the limits change.
Frequently asked questions
When does the answer have to be empty?
Exactly when m * n is different from the length of original. Every value must be used and every cell must be filled, so the two counts have to match.
Why is row i the slice from i * n to (i + 1) * n?
Rows hold n values each, so rows 0 to i - 1 use up the first i * n values. Row i starts right after them and takes the next n.
What is the time and space complexity?
O(m * n) time to copy every value once, and O(m * n) space for the returned grid.
How is this different from Reshape the Matrix?
Reshape the Matrix starts from a 2D grid and returns the original grid on a size mismatch. Here the input is already flat, so each row is a plain slice, and a mismatch returns an empty array.