Nested Array Generator - Problem
You're given a multi-dimensional array containing integers and other nested arrays. Your task is to create a generator function that yields all integers in the same order as they appear during an inorder traversal.
A multi-dimensional array is a recursive data structure where each element can be either:
- An integer value
- Another multi-dimensional array
Inorder traversal means we process elements from left to right, yielding integers immediately when encountered, and recursively traversing any nested arrays we find.
For example: [1, [2, 3], 4, [5, [6, 7]]] should yield: 1, 2, 3, 4, 5, 6, 7
The key challenge is implementing this as a generator that yields values lazily, rather than creating the entire flattened array upfront.
Input & Output
example_1.py โ Basic Nested Array
$
Input:
nested_list = [1, [2, 3], 4]
โบ
Output:
Generator yields: 1, 2, 3, 4
๐ก Note:
The generator traverses left to right: yields 1, enters [2,3] and yields 2 then 3, finally yields 4. Each value is produced lazily when requested.
example_2.py โ Deeply Nested Structure
$
Input:
nested_list = [[1, 2], 3, [4, [5, 6]]]
โบ
Output:
Generator yields: 1, 2, 3, 4, 5, 6
๐ก Note:
Deep nesting is handled recursively. The generator enters [1,2] yielding both values, then yields 3, enters [4,[5,6]] yielding 4, then recursively enters [5,6] to yield 5 and 6.
example_3.py โ Single Level Array
$
Input:
nested_list = [1, 2, 3, 4, 5]
โบ
Output:
Generator yields: 1, 2, 3, 4, 5
๐ก Note:
Edge case with no nesting - the generator simply yields each integer in order from left to right, demonstrating it works correctly for flat arrays too.
Constraints
- 1 โค nested_list.length โค 500
- The values of the integers in the nested list are in the range [-106, 106]
- Maximum nesting depth is 50
- The generator should yield values lazily (on-demand)
Visualization
Tap to expand
Understanding the Visualization
1
Smart Exploration
Instead of dumping all dolls at once, explore them systematically with a stack to remember your path
2
Immediate Collection
When you find a coin, collect it immediately - no need to wait
3
Recursive Delegation
When you find nested dolls, delegate the exploration to handle that branch
4
Memory Efficient
Only remember your current exploration path, not all coins discovered so far
Key Takeaway
๐ฏ Key Insight: Recursive generators with yield delegation combine the elegance of recursion with the efficiency of lazy evaluation, processing nested structures with minimal memory overhead.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code