Flatten 2D Vector - Problem
Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.
Implement the Vector2D class:
Vector2D(int[][] vec)initializes the object with the 2D vectorvec.next()returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls tonextare valid.hasNext()returnstrueif there are still some elements in the vector, andfalseotherwise.
Input & Output
Example 1 — Basic 2D Vector
$
Input:
vec = [[1,2],[3],[4]], operations = ["Vector2D","next","next","next","hasNext","hasNext","next","hasNext"]
›
Output:
[null,1,2,3,true,true,4,false]
💡 Note:
Vector2D iterator flattens [[1,2],[3],[4]]. next() returns 1,2,3,4 in sequence. hasNext() checks if more elements exist.
Example 2 — Empty Rows
$
Input:
vec = [[1,2],[],[3]], operations = ["Vector2D","next","next","hasNext","next","hasNext"]
›
Output:
[null,1,2,true,3,false]
💡 Note:
Empty middle row is skipped automatically. Elements 1,2,3 are returned in order despite empty row.
Example 3 — Single Row
$
Input:
vec = [[1,2,3,4,5]], operations = ["Vector2D","hasNext","next","hasNext"]
›
Output:
[null,true,1,true]
💡 Note:
Single row with multiple elements. hasNext() returns true, next() returns 1, still has more elements.
Constraints
- 1 ≤ vec.length ≤ 200
- 0 ≤ vec[i].length ≤ 500
- -500 ≤ vec[i][j] ≤ 500
- At most 105 calls to next and hasNext
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code