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: Iterator Design PatternInput 2D Vector:[1,2][3][4]Row 0Row 1Row 2Iterator Methods:• next() → return current element• hasNext() → check if more elementsSequential Access:1234next()next()next()next()Output: Elements accessed sequentially despite 2D structure
Understanding the Visualization
1
Input
2D vector [[1,2],[3],[4]] with mixed row lengths
2
Iterator
Provides next() and hasNext() methods for sequential access
3
Output
Elements returned in row-major order: 1,2,3,4
Key Takeaway
🎯 Key Insight: Use two pointers (row, col) to navigate 2D structure while providing 1D iterator interface
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