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
- The construction is possible exactly when
m * n == len(original). - When it is possible, slice
originalintomconsecutive chunks of lengthn, one per row. - The input is already in row-major order, matching the required fill order, so the mapping is direct with no permutation.
- 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 isoriginal[i * n:(i + 1) * n]. - Transposing the chunks: the fill is row-major, so consecutive chunks are rows, not columns.
- Overflowing
m * nin fixed-width languages: with both up to10^4the product reaches10^8, which fits in 64-bit but not 32-bit.