Algo-Sim › Low-Level Design
Flatten Nested List Iterator
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
Keep a stack of not-yet-visited items; hasNext opens lists on top until an integer is there, so flattening happens lazily.
Problem
A nested list holds integers and other nested lists, to any depth. Build an iterator over its integers in order, from left to right: next() returns the next integer and hasNext() says whether any are left. The caller loops while (hasNext()) next().
Constraints
- 1 ≤ nestedList.length ≤ 500
- -10⁶ ≤ every integer ≤ 10⁶
- Lists may be empty and nested to any depth
Edge cases to test
- Empty nested lists:
[[], []] - Deep nesting
- An integer at the top level
Follow-up questions
- Why flatten lazily?
- Eager flattening uses O(n) memory up front; a stack of iterators uses O(depth) and works on huge inputs.
- Why must
hasNextdo the work? - It has to skip empty lists to know if another integer exists;
nextcan then just pop.
Solution
Java
public class NestedIterator implements Iterator<Integer> {
private final Deque<NestedInteger> stack = new ArrayDeque<>();
public NestedIterator(List<NestedInteger> nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--) stack.push(nestedList.get(i));
}
@Override
public boolean hasNext() {
while (!stack.isEmpty() && !stack.peek().isInteger()) {
List<NestedInteger> items = stack.pop().getList();
for (int i = items.size() - 1; i >= 0; i--) stack.push(items.get(i));
}
return !stack.isEmpty();
}
@Override
public Integer next() {
hasNext();
return stack.pop().getInteger();
}
}Python
class NestedIterator:
def __init__(self, nestedList):
self.stack = nestedList[::-1]
def hasNext(self):
while self.stack and not self.stack[-1].isInteger():
self.stack.extend(self.stack.pop().getList()[::-1])
return bool(self.stack)
def next(self):
self.hasNext()
return self.stack.pop().getInteger()C++
#include <bits/stdc++.h>
using namespace std;
class NestedIterator {
vector<const NestedInteger *> stack;
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--) stack.push_back(&nestedList[i]);
}
int next() {
hasNext();
int value = stack.back()->getInteger();
stack.pop_back();
return value;
}
bool hasNext() {
while (!stack.empty() && !stack.back()->isInteger()) {
const vector<NestedInteger> &items = stack.back()->getList();
stack.pop_back();
for (int i = items.size() - 1; i >= 0; i--) stack.push_back(&items[i]);
}
return !stack.empty();
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)