Convert 1D Array Into 2D Array

Validate dimensions match the input length, then copy contiguous slices via indexing.

Easy
Time O(m*n) Space O(m*n)
LeetCode
3 min read
matrix simulation

Problem#

Given a 1D array original and dimensions m, n, return an m x n 2D array filled row-by-row from original, or an empty array if the length doesn’t equal m * n.

Examples#

  • original = [1,2,3,4], m = 2, n = 2[[1,2],[3,4]]
  • original = [1,2,3], m = 1, n = 3[[1,2,3]]
  • original = [1,2], m = 1, n = 1[]

Constraints#

  • 1 <= original.length <= 5 * 10^4, 1 <= original[i] <= 10^5, 1 <= m, n <= 4 * 10^4.

Approach#

Reject if m * n != original.size(). Allocate the result and use i = k / n, j = k % n to map flat index k to its 2D position — or copy row slices directly.

Solution#

Convert 1D Array Into 2D Array
class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if ((long)m * n != (long)original.size()) return {};
vector<vector<int>> ans(m, vector<int>(n));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
ans[i][j] = original[i * n + j];
return ans;
}
};

Editorial#

The (long)m * n cast prevents overflow on large dimensions. Once validated, the index map original[i*n + j] is the standard row-major flattening.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.