15% off all plans & roadmaps Use code
See plansFlatten Nested List Iterator
- LeetCode 341
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Return the integers of a nested list one at a time, in left-to-right order. Keep a stack of unvisited elements and open a list only when it reaches the top.
Problem
You are given a nested list of integers, nestedList. Each element is either an integer or a list. That list can hold integers or more lists.
Implement the NestedIterator class:
NestedIterator(List<NestedInteger> nestedList)initializes the iterator withnestedList.int next()returns the next integer in the nested list.boolean hasNext()returnstrueif integers remain, andfalseotherwise.
Your code is tested with this pseudocode. Create the iterator from nestedList and set res to an empty list. While iterator.hasNext() is true, append iterator.next() to res. Return res. If res matches the expected flattened list, your code is correct.
Example 1
Input: nestedList = [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: Calling next until hasNext returns false gives [1,1,2,1,1].
Example 2
Input: nestedList = [1,[4,[6]]] Output: [1,4,6] Explanation: Calling next until hasNext returns false gives [1,4,6].
Constraints
1 <= nestedList.length <= 500- The values of the integers in the nested list are in the range
[-10^6, 10^6].
Constraints that matter
- The top-level list holds at most 500 items, but nesting can go deeper, so a recursive walk can hit recursion limits on deep input.
- Integers are within plus or minus 10^6, so every language's int type holds them and no overflow handling is needed.
nextandhasNextare called one at a time with pauses between, so the design must keep its place between calls instead of finishing the walk in one go.- Empty lists can appear at any depth, so
hasNextmust skip them and keep looking rather than give up.
Hints
Hint 1
This is the iterator design pattern.
Hint 2
The beginner version does all the work in the constructor.
Solution
Intuition
This is the iterator design pattern. You hand out one element per call and hide the nesting from the caller. The problem forces you to pause after each integer and resume later, which a recursive walk cannot do, because its call stack unwinds on every return. So you keep the traversal state yourself, as an explicit stack that simulates depth-first search.
Picture a pile of nested gift boxes, with the outermost box on top. The pile is the stack, and you open a box only when it reaches the top, while a bare number on top is handed over at once.
The next answer is always the first integer a left-to-right walk would reach. The top of the stack is always the next thing to inspect. An integer on top is ready to return. A list on top must be opened before anything else happens.
A stack is last-in, first-out, so children must go in reverse. If you push [1, 2] as 1 and then 2, the 2 comes out first. Pushing in reverse puts the first child on top, and the walk order holds.
Worked example
Input: nestedList = [[1, [2, [3, 4]], 5], [6]] Output: [1, 2, 3, 4, 5, 6] Explanation: The top-level list has two items, [1, [2, [3, 4]], 5] and [6]. Reading left to right and opening each nested list in place gives 1, 2, 3, 4, 5, then 6.
Approach 1: Brute force, flatten eagerly
The beginner version does all the work in the constructor. A recursive helper walks the input, appends each integer to an array, and recurses into each list it meets. After that, next returns array entries in order using a counter.
The result is correct because the recursion visits every element in left-to-right order. The cost is that every integer is copied before the caller asks for the first one.
Steps
- In the constructor, set
valuesto an empty array andposto 0. - Call a recursive helper on
nestedList. - For each element in the helper, append the integer if it is an integer, or recurse into it if it is a list.
nextreturnsvalues[pos]and incrementspos.hasNextreturns true whileposis less than the length ofvalues.
Dry run
Constructor on [[1, [2, [3, 4]], 5], [6]]. The helper walks left to right and recurses into each list. It appends 1, then 2, 3, 4, then 5, then 6. The result is values = [1, 2, 3, 4, 5, 6] and pos = 0.
Then next() returns values[0] (1), then values[1] (2), and so on. After 6 is returned, pos equals 6 and hasNext() returns false.
Complexity
| Time | O(N) constructor, O(1) per call |
|---|---|
| Space | O(N) |
Let N be the number of list and integer objects in the input. The constructor visits each object exactly once, so it does O(N) work. Each next and hasNext reads or increments a counter, which is O(1). The values array holds every integer, and the recursion adds up to D frames, where D is the nesting depth.
PythonTested in our runner
from typing import List, Optional
class NestedIterator:
def __init__(self, nestedList: List[NestedInteger]):
self.values = []
self.pos = 0
self._flatten(nestedList)
def _flatten(self, items: List[NestedInteger]) -> None:
for item in items:
if item.isInteger():
self.values.append(item.getInteger())
else:
self._flatten(item.getList())
def next(self) -> int:
value = self.values[self.pos]
self.pos += 1
return value
def hasNext(self) -> bool:
return self.pos < len(self.values)The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Lazy unpacking with a stackOptimalDesign (General/Specific)
What's slow: the eager version does all the work up front, even when the caller reads only two numbers. It also stores a full copy of every integer, when the input already holds them.
The insight that fixes it: keep the original lists and a stack of unvisited elements. Open a list only when it reaches the top, and stop at the first integer. Each list is opened once, so the total work over a full traversal stays linear.
Why it is correct. The stack always holds every unvisited element, with the earliest one on top, in original left-to-right order. Opening a list replaces it with its children in that same order, so nothing is lost or reordered. hasNext stops only at an integer, so no integer is ever skipped.
Steps
- In the constructor, push the top-level elements onto the stack in reverse order.
- In
hasNext, look at the top element of the stack. - If the top is an integer, return true.
- If the top is a list, pop it and push its children in reverse order.
- Repeat until the top is an integer or the stack is empty, then return false.
- In
next, callhasNextand pop the top integer.
Dry run
The input is [[1, [2, [3, 4]], 5], [6]]. Call the outer list A, so A is [1, [2, [3, 4]], 5], and the second item is [6]. The table traces every call. Stack contents are listed top first.
| Step | Call and action | Stack, top first | Returned so far |
|---|---|---|---|
| 1 | Constructor pushes [6], then A | A, [6] | none |
| 2 | hasNext opens A and pushes 5, then [2,[3,4]], then 1 | 1, [2,[3,4]], 5, [6] | none |
| 3 | hasNext sees 1 on top and returns true. next pops 1 | [2,[3,4]], 5, [6] | 1 |
| 4 | hasNext opens [2,[3,4]] and pushes [3,4], then 2 | 2, [3,4], 5, [6] | 1 |
| 5 | next pops 2 | [3,4], 5, [6] | 1, 2 |
| 6 | hasNext opens [3,4] and pushes 4, then 3 | 3, 4, 5, [6] | 1, 2 |
| 7 | next pops 3 | 4, 5, [6] | 1, 2, 3 |
| 8 | next pops 4 | 5, [6] | 1, 2, 3, 4 |
| 9 | next pops 5 | [6] | 1, 2, 3, 4, 5 |
| 10 | hasNext opens [6] and pushes 6. next pops 6 | empty | 1, 2, 3, 4, 5, 6 |
| 11 | hasNext finds the stack empty | empty | returns false |
The last returned value is 6, which matches the expected output.
Complexity
| Time | O(N) total, amortized O(1) per call |
|---|---|
| Space | O(N) |
Let N be the number of list and integer objects in the input. Each element is pushed at most once, and each list is popped at most once, so all calls together do O(N) pushes and pops. Dividing that total across the full traversal gives amortized O(1) per call, although one hasNext can open many empty lists at once. The stack never holds more than N references, so extra space is O(N) in the worst case, for example a flat list of 500 integers.
PythonTested in our runner
from typing import List, Optional
class NestedIterator:
def __init__(self, nestedList: List[NestedInteger]):
# Reverse once so the first element sits at the end, which is the top.
self.stack = list(reversed(nestedList))
def next(self) -> int:
self.hasNext()
return self.stack.pop().getInteger()
def hasNext(self) -> bool:
while self.stack:
top = self.stack[-1]
if top.isInteger():
return True
self.stack.pop()
children = top.getList()
# Push children reversed so the first child ends up on top.
for child in reversed(children):
self.stack.append(child)
return FalseCommon mistakes
self.stack = nestedListwith no reversal. Pops return the last element first, so the output runs backwards. Reverse the list once before using it as a stack.for child in children:pushes the children in forward order. The top level looks right, but[1, [2, 3]]yields 1, 3, 2. Push children in reverse, the same way as the top level.- An
ifwhere the loop should be. After[[1]]is opened, the top is a list again, andnextcallsgetIntegeron a list. Use awhileloop that runs until the top is an integer or the stack is empty. return Falsewhen an empty list is popped. For[[], 5], this reports no next value even though 5 remains. An empty list should disappear, so keep looping.return len(self.stack) > 0as the body ofhasNext. For[[]], this reports true, andnextthen fails. Check that the top is an integer after unpacking.
Edge cases
[[]]:hasNextreturns false, and no call tonextis valid.[[], [[]], 7]: the firstnextreturns 7, because empty lists are skipped.[-1000000, [1000000]]: returns -1000000, then 1000000. Both fit in a 32-bit int.[[[[1]]]]: onehasNextcall opens four lists before it returns true with 1 on top.- Calling
hasNexttwice in a row: both calls return the same answer. Opening a list only moves its children, so the next value does not change. [5]:hasNextis true,nextreturns 5, andhasNextthen returns false.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Flatten Nested List Iterator, with how to answer them.
Unlock the follow-upsFlatten Nested List Iterator FAQ
What is the time complexity of Flatten Nested List Iterator?
The lazy stack design does O(N) total work over a full traversal, where N counts every list and integer in the input. Each single call is amortized O(1), although one hasNext can open many empty lists at once. The brute force design does O(N) work in the constructor and O(1) per call.
Why use a stack for Flatten Nested List Iterator?
A stack returns the most recently pending element first, which matches how depth-first traversal opens nested lists. It also keeps the place between calls, so next and hasNext can pause and resume. A recursive helper cannot pause, because its call stack unwinds on return.
Can Flatten Nested List Iterator be solved in O(1) extra space?
No, not with this design. In a flat list of 500 integers, the stack holds up to 500 references at once. Keeping one index per open list uses O(D) space for nesting depth D, which is still not constant for deep input.
Why push the children of a list in reverse order?
The stack pops the last item pushed first. Pushing the children in reverse puts the first child on top, so it comes out first. Skipping the reversal flips the order inside each nested list while the top level still looks correct.
Is the recursive flatten approach acceptable here?
It gives the correct output, and the brute force version on this page uses it. It fails the iterator requirement because all the work happens in the constructor. Very deep nesting can also exceed Python's default recursion limit.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns