NeetCode #973LC-2649MediumJavaScript
← Back to All Problems#973 · #2649 · Nested Array Generator(嵌套数组生成器)
📌 Problem Statement & Constraints
Implement the generator function
inorderTraversal(arr), which yields every integer of a multi-level nested array in pre-order.💡 Core Algorithmic Approaches
- Declare it with
function*and iterate over the elements. - If an element is an array, delegate to a recursive generator with
yield*. - Otherwise yield the integer directly.
yield*forwards every value produced by the sub-generator to the caller, so no manual loop is needed.
💻 Benchmark Python3 Implementation
var inorderTraversal = function*(arr) {
for (const x of arr) {
if (Array.isArray(x)) {
yield* inorderTraversal(x); // delegate to the sub-generator
} else {
yield x;
}
}
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(N): every element is visited once.
💾 Space Complexity
O(D): D is the nesting depth (generator stack).
⚠️ Interview Pitfalls & Follow-ups
- Writing
yield inorderTraversal(x): that yields the generator object itself instead of its values;yield*is required. - Forwarding the sub-generator with a manual
for...of: correct but more verbose thanyield*. - Omitting the
Array.isArraytest: a non-array element would be treated as iterable and throw. - Collecting into an array in a normal function: the problem requires the generator interface.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.