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.
Examples
Example 1
| |
Constraints
0 <= vec.length <= 2000 <= vec[i].length <= 500-500 <= vec[i][j] <= 500- At most
105calls will be made tonextandhasNext.
Follow up
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
Solution
Method 1 – Two Pointers Iterator
Intuition
The key idea is to use two pointers to track the current row and column in the 2D vector. We advance the pointers to skip empty rows and always point to the next available element. This allows us to flatten the 2D vector on-the-fly without extra space.
Approach
- Initialize two indices:
rowfor the current row andcolfor the current column. - In
hasNext(), advancerowandcolto skip empty rows or columns until a valid element is found or the end is reached. - In
next(), callhasNext()to ensure the pointers are at a valid element, then return the current element and incrementcol. - Handle edge cases where rows may be empty or the entire vector is empty.
Code
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(1)pernext()andhasNext()call (amortized, since each element is visited once). - 🧺 Space complexity:
O(1)(no extra space except pointers).