NeetCode #911LC-2022EasyMath & Geometry
← Back to All Problems

#911 · #2022 · Convert 1D Array Into 2D Array(将一维数组转变成二维数组)

📌 Problem Statement & Constraints

Given a 1D array original and two integers m and n, build an m x n 2D array by filling it row by row with the elements of original in order. If the construction is impossible, return an empty 2D array. Constraints: 1 <= original.length <= 5 * 10^4, 1 <= m, n <= 10^4.

💡 Core Algorithmic Approaches

  1. The construction is possible exactly when m * n == len(original).
  2. When it is possible, slice original into m consecutive chunks of length n, one per row.
  3. The input is already in row-major order, matching the required fill order, so the mapping is direct with no permutation.
  4. Otherwise return an empty list, which is the specified signal for an impossible reshape.

💻 Benchmark Python3 Implementation

class Solution:
    def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
        if m * n != len(original):
            return []
        res = []
        for i in range(m):
            res.append(original[i * n:(i + 1) * n])
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m * n): each element is copied once.
💾 Space Complexity
O(m * n): the output matrix.

⚠️ Interview Pitfalls & Follow-ups

  • Returning a partially filled matrix on a size mismatch: the specification requires an empty list in that case.
  • Slicing with the wrong step: consecutive rows start at multiples of n, so the slice is original[i * n:(i + 1) * n].
  • Transposing the chunks: the fill is row-major, so consecutive chunks are rows, not columns.
  • Overflowing m * n in fixed-width languages: with both up to 10^4 the product reaches 10^8, which fits in 64-bit but not 32-bit.