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 iterator
  • int next() - Return the next integer in flattened order
  • boolean 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
Initial: [[1,1],2,[1,1]][1,1]2[1,1]StackAfter hasNext() flattening112[1,1]Ready!Lazy Flattening with StackElements are processed only when needed
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

n
2n
โœ“ Linear Growth
Space Complexity
O(d)

O(d) where d is the maximum depth of nesting, for the stack storage

n
2n
โœ“ 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
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
67.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen