The Flatten 2D Vector interview question asks you to implement an iterator for a list of lists. You are given a 2D array (e.g., [[1, 2], [], [3]]) and need to provide next() and hasNext() methods that allow a user to traverse all the elements as if they were in a single flat 1D list.
Companies like Airbnb and Google ask the Flatten 2D Vector coding problem to test a candidate's mastery of the Iterator interview pattern. It evaluations your ability to manage multiple pointers (one for the outer list and one for the inner list) and handle "empty" sub-lists correctly without crashing or skipping elements.
This is a Two-Pointer Simulation problem.
row: Index of the current sub-list.col: Index of the element within the current sub-list.hasNext() (The Core): This method should do the heavy lifting. If the current col is at the end of the current row, increment row and reset col until you find a non-empty sub-list or reach the end of the 2D array.next(): Simply call hasNext() to ensure you are at a valid element, then return vec[row][col++].Input: [[1, 2], [], [3]]
row=0, col=0.next(): Returns vec[0][0] (1). col=1.next(): Returns vec[0][1] (2). col=2.next():
hasNext() sees col=2 is end of vec[0].row=1. vec[1] is empty.row=2. col reset to 0.vec[2][0] (3).next() is called to find the next valid element. It’s much cleaner to handle the skipping of empty lists inside hasNext().row has exceeded the 2D array size before checking for empty lists.Always implement iterators Lazily. The goal is to provide elements one-by-one without pre-processing the entire dataset. This is a foundational Design interview pattern for large-scale data systems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Peeking Iterator | Medium | Solve | |
| Zigzag Iterator | Medium | Solve | |
| Dot Product of Two Sparse Vectors | Medium | Solve | |
| RLE Iterator | Medium | Solve | |
| Design Compressed String Iterator | Easy | Solve |