Flatten 2D Vector - Problem

You're tasked with designing an iterator that can seamlessly traverse through a 2D vector as if it were a flat, one-dimensional array. Think of it like reading a book page by page, word by word, from left to right and top to bottom.

Your Vector2D class needs to implement:

  • Constructor: Vector2D(int[][] vec) - Initialize with a 2D vector
  • next(): Return the next element and advance the pointer
  • hasNext(): Check if there are more elements to iterate over

Challenge: You need to handle empty rows gracefully and ensure optimal space usage - don't flatten everything upfront!

Example: Given [[1,2],[3],[4,5,6]], your iterator should return elements in order: 1 → 2 → 3 → 4 → 5 → 6

Input & Output

example_1.py — Basic Usage
$ Input: vec = [[1,2],[3],[4,5,6]]<br/>Operations: hasNext(), next(), next(), hasNext(), next(), hasNext(), next(), next(), hasNext()
Output: [true, 1, 2, true, 3, true, 4, 5, false]
💡 Note: The iterator traverses through all elements in row-major order: 1→2→3→4→5→6, then returns false when no more elements exist.
example_2.py — Empty Rows
$ Input: vec = [[1],[],[2,3]]<br/>Operations: hasNext(), next(), hasNext(), next(), next(), hasNext()
Output: [true, 1, true, 2, 3, false]
💡 Note: Empty rows are automatically skipped. The iterator goes directly from element 1 to element 2, ignoring the empty middle row.
example_3.py — All Empty
$ Input: vec = [[],[],[]]<br/>Operations: hasNext()
Output: [false]
💡 Note: When all rows are empty, hasNext() immediately returns false as there are no elements to iterate over.

Visualization

Tap to expand
Iterator State ProgressionInitial State: [[1,2],[],[3,4]]12empty34row=0, col=0Step 1: Start at (0,0)After next() call12empty34row=0, col=1Step 2: Return 1, advance colSkip empty row12skip34row=2, col=0Step 3: Skip to next validAlgorithm FlowhasNext() calledadvanceToNext()Skip empty rowsReturn resultKey Benefits of Two Pointers:• O(1) space complexity - no extra arrays• O(1) initialization time• Lazy evaluation - process only when needed• Automatic empty row handling• Clean iterator design patternTime Complexity:• Each element visited at most once• O(1) amortized per operation
Understanding the Visualization
1
Position Tracking
Keep track of current row and column position in the 2D structure
2
Lazy Evaluation
Only advance position when hasNext() or next() is called, not during initialization
3
Empty Row Handling
Automatically skip over empty rows to find the next valid element
4
Boundary Detection
Detect when we've reached the end of all rows to return false for hasNext()
Key Takeaway
🎯 Key Insight: Use two pointers to maintain current position in 2D structure. The advance-to-next helper function handles empty row skipping, making the iterator robust and memory-efficient.

Time & Space Complexity

Time Complexity
⏱️
O(n) initialization, O(1) per operation

Need to traverse all n elements once during construction, then each operation is constant time

n
2n
Linear Growth
Space Complexity
O(n)

Store all n elements in additional flat array

n
2n
Linearithmic Space

Constraints

  • 0 ≤ vec.length ≤ 200
  • 0 ≤ vec[i].length ≤ 500
  • -500 ≤ vec[i][j] ≤ 500
  • At most 105 calls to next and hasNext
  • Follow up: Can you implement it without flattening the 2D vector?
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28 Apple 22 Twitter 18
42.0K Views
Medium-High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen