SDE & MLE Prep

341. Flatten Nested List Iterator

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)