NeetCode #965LC-2625MediumJavaScript
← Back to All Problems#965 · #2625 · Flatten Deeply Nested Array(扁平化嵌套数组)
📌 Problem Statement & Constraints
Given a multi-level nested array
arr and a depth n, return a new array flattened to depth n. The depth counts nesting levels, so n = 0 returns a shallow copy of the input.💡 Core Algorithmic Approaches
- Recurse over the elements: if an element is an array and the current depth is below
n, flatten it further; otherwise place it into the result. - Carry a
depthparameter to track how many levels have already been flattened. - With
n = 0no nested array is expanded, so nesting is preserved. - An iterative version with an explicit stack avoids the recursion limit for very deep inputs.
💻 Benchmark Python3 Implementation
var flat = function(arr, n) {
const res = [];
const go = (a, depth) => {
for (const x of a) {
if (Array.isArray(x) && depth < n) {
go(x, depth + 1); // still allowed to expand
} else {
res.push(x);
}
}
};
go(arr, 0);
return res;
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(N): N is the total number of elements.
💾 Space Complexity
O(D): D is the flattening depth (recursion stack).
⚠️ Interview Pitfalls & Follow-ups
- Writing the depth test as
depth <= n: that expands one level too many; the strict comparison is correct. - Recursing when
n = 0: no nested array should be expanded in that case. - Using the built-in
arr.flat(n): the exercise expects a hand-written implementation. - Omitting the
Array.isArraytest: plain objects must not be expanded.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.