Flatten Nested List Iterator - Problem
You're given a nested list of integers where each element can be either an integer or another list containing integers or more nested lists. Your task is to design an iterator that can traverse through all the integers in a flattened manner.
Think of it like exploring a filing cabinet with folders inside folders - you need to visit every document (integer) regardless of how deeply nested it is!
Implement the NestedIterator class:
NestedIterator(List<NestedInteger> nestedList)- Initialize the iteratorint next()- Return the next integer in flattened orderboolean hasNext()- Check if there are more integers to visit
Example: Given [[1,1],2,[1,1]], your iterator should return 1, 1, 2, 1, 1 in that order.
Input & Output
example_1.py โ Basic nested list
$
Input:
nestedList = [[1,1],2,[1,1]]
โบ
Output:
[1,1,2,1,1]
๐ก Note:
The iterator should flatten the nested structure and return each integer in order: first 1 and 1 from [1,1], then 2, then 1 and 1 from the second [1,1].
example_2.py โ Deeply nested
$
Input:
nestedList = [1,[4,[6]]]
โบ
Output:
[1,4,6]
๐ก Note:
The nested structure contains: 1 at the top level, then 4 inside a list, then 6 inside a nested list within that list.
example_3.py โ Empty lists
$
Input:
nestedList = [1,[],[],[4,[]]]
โบ
Output:
[1,4]
๐ก Note:
Empty lists should be ignored. Only the integers 1 and 4 are returned, skipping all empty nested lists.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Put all top-level elements on stack in reverse order
2
hasNext() check
If top is a list, open it and put contents on stack
3
Ready for next()
Top of stack is guaranteed to be an integer
4
Return integer
Pop and return the integer from stack top
Key Takeaway
๐ฏ Key Insight: The stack simulates recursive traversal while providing lazy evaluation - we only flatten nested lists when we actually need to access their elements, making it memory efficient and truly iterator-like.
Time & Space Complexity
Time Complexity
O(1) amortized
Each element is pushed and popped exactly once, so amortized O(1) per operation
โ Linear Growth
Space Complexity
O(d)
O(d) where d is the maximum depth of nesting, for the stack storage
โ Linear Space
Constraints
- 1 โค nestedList.length โค 500
- The values of the integers in the nested list are in the range [-106, 106]
- The total number of integers in the nested list is at most 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code