⚡Flashcard Drill➔
NeetCode #373LC-341MediumStack
← Back to All Problems

#373 · #341 · Flatten Nested List Iterator(扁平化嵌套列表迭代器)

📌 Problem Statement & Constraints

This is an interactive problem. You are given a nested list of integers, where each element is either an integer or a list. Implement NestedIterator with next() and hasNext(), flattening the structure. Constraints: the total number of integers is at most 10^4; the nesting depth is at most 1000.

💡 Core Algorithmic Approaches

  1. Use an explicit stack of the nested list, with the elements in reverse order so the next element is on top.
  2. hasNext normalises the stack: while the top is a list, pop it and push its elements in reverse.
  3. Once the top is an integer, hasNext is true and next simply pops it.
  4. Lazy flattening is important: eagerly expanding the whole structure would cost O(total size) up front and could blow the recursion depth.

💻 Benchmark Python3 Implementation

class NestedIterator:
    def __init__(self, nestedList: ["NestedInteger"]):
        # reversed so the first element ends up on top of the stack
        self.st = list(reversed(nestedList))

    def next(self) -> int:
        return self.st.pop().getInteger()

    def hasNext(self) -> bool:
        while self.st:
            top = self.st[-1]
            if top.isInteger():
                return True
            self.st.pop()
            # push the inner list reversed so its first element is on top
            self.st.extend(reversed(top.getList()))
        return False

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1) amortised per operation: each element is pushed and popped once over the iterator's lifetime.
💾 Space Complexity
O(n) for the stack, where n is the total number of elements.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting to reverse when extending: without the reversal, the elements would be consumed in the wrong order.
  • Eagerly flattening in the constructor: it works but costs O(n) up front and requires recursion or an explicit stack anyway.
  • Returning True from hasNext without normalising: the top might be a list, so next would fail.
  • Using recursion to flatten: the nesting depth can reach 1000, which risks exceeding the recursion limit.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

扁平化嵌套列表迭代器

给你一个嵌套的整数列表 nestedList。每个元素要么是一个整数,要么是一个列表 —— 该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。实现扁平化迭代器 NestedIterator 类: NestedIterator(nestedList) 初始化迭代器; next() 返回下一个整数; hasNext() 若仍有整数则返回 true,否则返回 false。约束:1 ≤ nestedList.length ≤ 500;嵌套列表中的元素范围在 [-10^6, 10^6] 内;最多调用 10^4 次 next 和 hasNext。

核心要点

  • 方案一 · 惰性展开(推荐) :用栈保存待处理的元素(倒序压栈,使栈顶是最左元素)。 hasNext() 时不断检查栈顶:若是整数则就绪;若是列表则 展开 并把其元素倒序压栈。
  • 为什么用倒序压栈 :栈是后进先出,倒序压入才能保证「最左元素在栈顶」。
  • 方案二 · 构造时全部展开 :在 __init__ 中递归展开成扁平列表, next / hasNext 只是下标访问。实现简单但失去了「惰性」的优势。
  • 惰性展开的价值 :若列表极深或极大,构造时就全部展开会浪费内存;惰性展开只在需要时处理。

常见陷阱

  • 展开时正序压栈 :会导致最右元素在栈顶,遍历顺序颠倒。必须倒序压入。
  • hasNext 用 if 而非 while :栈顶可能是多层嵌套的列表,需要循环展开直到露出整数。
  • next 中不调用 hasNext :若栈顶仍是列表, pop().getInteger() 会报错。
  • 构造时递归展开但不处理深层嵌套 :递归深度可能很大(虽然本题约束较浅),惰性栈方案无此问题。

参考实现

class NestedIterator:
    def __init__(self, nestedList: list):
        # 倒序压栈,使栈顶为最左元素
        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()
            for item in reversed(top.getList()):
                self.stack.append(item)
        return False