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 vector vec.
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.

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
Flatten 2D Vector INPUT vec = [[1,2],[3],[4]] 1 2 [0] 3 [1] 4 [2] Two Pointers: outer (row index) inner (col index) Operations: Vector2D, next, next, next, hasNext, hasNext, next, hasNext ALGORITHM STEPS 1 Initialize outer=0, inner=0 2 advanceToValid() Skip empty rows 3 next() Return vec[outer][inner++] 4 hasNext() Check valid position exists Execution Trace: next() --> 1 (0,0) next() --> 2 (0,1) next() --> 3 (1,0) hasNext() --> true hasNext() --> true next() --> 4 (2,0) hasNext() --> false FINAL RESULT Flattened Order: 1 2 3 4 Output Array: [null, 1, 2, 3, true, true, 4, false] OK - All operations complete Complexity Analysis: Time: O(1) amortized per op Space: O(1) extra Iterator State: Active Done Key Insight: Use two pointers (outer, inner) to track position in 2D array. The advanceToValid() helper method skips empty inner arrays by incrementing outer when inner reaches row end. This enables O(1) amortized time per operation while using only O(1) extra space for the pointer variables. TutorialsPoint - Flatten 2D Vector | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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