341. Flatten Nested List Iterator
Asked at 17Apple53Meta38Amazon29Google29Bloomberg8.3Microsoft7.5Adobe63Mixpanel100X97OpenAI74Warnermedia70Aurora62Yahoo61LinkedIn53Tesla52Walmart Labs43DE Shaw38
Problem
Design NestedIterator over a nested list in which each element is an integer or another nested list. next() returns the integers one by one in left-to-right order, flattening the nesting, and hasNext() says whether any remain.
Example: [[1,1],2,[1,1]] → 1,1,2,1,1; [1,[4,[6]]] → 1,4,6
Keep a stack of lists in reverse order. hasNext does the real work: while the top is a list, pop it and push its children reversed; stop when the top is an integer.
Complexity: amortized O(1) per element.
class NestedInteger: # LeetCode's interface (minimal stand-in)
def __init__(self, v): self.v = v
def isInteger(self): return isinstance(self.v, int)
def getInteger(self): return self.v
def getList(self): return self.v
class NestedIterator:
def __init__(self, nestedList: List["NestedInteger"]):
self.st = nestedList[::-1]
def next(self) -> int:
return self.st.pop().getInteger() # hasNext() guarantees an integer on top
def hasNext(self) -> bool:
while self.st and not self.st[-1].isInteger():
self.st.extend(reversed(self.st.pop().getList()))
return bool(self.st)
def wrap(x): return NestedInteger(x if isinstance(x, int) else [wrap(y) for y in x])
it, out = NestedIterator([wrap(x) for x in [[1, 1], 2, [1, 1]]]), []
while it.hasNext():
out.append(it.next())
assert out == [1, 1, 2, 1, 1]
it, out = NestedIterator([wrap(x) for x in [1, [4, [6]], [[]]]]), []
while it.hasNext():
out.append(it.next())
assert out == [1, 4, 6]
interface NestedInteger { // provided by LeetCode
boolean isInteger();
Integer getInteger();
List<NestedInteger> getList();
}
class NI implements NestedInteger { // local stand-in for tests
private final Integer v; private final List<NestedInteger> l;
NI(int v) { this.v = v; this.l = null; }
NI(NestedInteger... xs) { this.v = null; this.l = List.of(xs); }
public boolean isInteger() { return v != null; }
public Integer getInteger() { return v; }
public List<NestedInteger> getList() { return l; }
}
class NestedIterator implements Iterator<Integer> {
private final Deque<NestedInteger> st = new ArrayDeque<>();
public NestedIterator(List<NestedInteger> nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--) st.push(nestedList.get(i));
}
@Override
public Integer next() { hasNext(); return st.pop().getInteger(); }
@Override
public boolean hasNext() {
while (!st.isEmpty() && !st.peek().isInteger()) {
List<NestedInteger> l = st.pop().getList();
for (int i = l.size() - 1; i >= 0; i--) st.push(l.get(i));
}
return !st.isEmpty();
}
}
type NestedInteger struct { // provided by LeetCode (a minimal stand-in)
isInt bool
val int
list []*NestedInteger
}
func (this NestedInteger) IsInteger() bool { return this.isInt }
func (this NestedInteger) GetInteger() int { return this.val }
func (this NestedInteger) GetList() []*NestedInteger { return this.list }
type NestedIterator struct {
st []*NestedInteger // reversed: the next element is on top
}
func Constructor(nestedList []*NestedInteger) *NestedIterator {
st := make([]*NestedInteger, len(nestedList))
for i, x := range nestedList {
st[len(nestedList)-1-i] = x
}
return &NestedIterator{st: st}
}
func (this *NestedIterator) Next() int {
top := this.st[len(this.st)-1] // HasNext() left an integer on top
this.st = this.st[:len(this.st)-1]
return top.GetInteger()
}
func (this *NestedIterator) HasNext() bool {
for len(this.st) > 0 && !this.st[len(this.st)-1].IsInteger() { // unpack lists lazily
top := this.st[len(this.st)-1]
this.st = this.st[:len(this.st)-1]
l := top.GetList()
for i := len(l) - 1; i >= 0; i-- {
this.st = append(this.st, l[i])
}
}
return len(this.st) > 0
}