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
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
✓ Linear Growth
Space Complexity
O(n)
Store all n elements in additional flat array
⚡ 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?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code