The Flatten Nested List Iterator interview question asks you to build a specialized iterator that can traverse a deeply nested data structure. You are given a list of "NestedIntegers," each of which is either a single integer or another list of NestedIntegers. Your task is to implement next() and hasNext() methods so that a user can iterate through all integers in the structure as if they were in a simple 1D array.
This is a classic Design interview pattern question used by companies like LinkedIn, Netflix, and Apple. It evaluates your ability to handle recursion and state management simultaneously. Interviewers want to see if you can implement a "lazy" iterator—one that only does the work necessary to find the next integer—rather than simply flattening the entire list into memory upfront, which is inefficient for massive datasets.
The most robust approach uses a Stack-based Iterator pattern.
hasNext() is called, you look at the top iterator. If it points to another list, you push a new iterator for that sub-list onto the stack.next() call.Consider the input: [[1, 1], 2, [3, 4]].
[1, 1]. It pushes an iterator for [1, 1] onto the stack.1 from the top iterator.[1, 1] iterator is exhausted, it is popped, and the stack returns to the main list iterator, which now points to 2.[1, [], [2]]. A naive hasNext() might return true for the empty list but then fail to find an integer.When designing iterators for recursive structures, always think about the Stack or Recursion as your primary tool. Practice the "lazy" approach, as it demonstrates that you understand the trade-offs between time and space complexity in system design. Mastering this Iterator interview pattern is key to solving many tree and graph traversal problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Binary Search Tree Iterator | Medium | Solve | |
| Binary Search Tree Iterator II | Medium | Solve | |
| Implement Queue using Stacks | Easy | Solve | |
| Implement Stack using Queues | Easy | Solve | |
| N-ary Tree Preorder Traversal | Easy | Solve |