Flatten 2D Vector Problem
Description
LeetCode Problem 251.
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.
Example 1:
Input
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
Output
[null, 1, 2, 3, true, true, 4, false]
Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next(); // return 1
vector2D.next(); // return 2
vector2D.next(); // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next(); // return 4
vector2D.hasNext(); // return False
Constraints:
0 <= vec.length <= 2000 <= vec[i].length <= 500-500 <= vec[i][j] <= 500- At most
10^5calls will be made tonextandhasNext.
Follow up: As an added challenge, try to code it using only iterators in C++ or iterators in Java.
Solution
Approach: Two Indices
Copying every value into one flat list would work, but it uses extra memory and is not really an iterator. Instead we keep the input and two indices: row and col, the position of the next element to return.
The only difficulty is empty rows, and the end of a row. A helper skipEmpty moves forward while col is past the end of the current row: it goes to the next row and sets col = 0. After it runs, either (row, col) points at a real element, or row is past the last row and nothing is left.
next(): callskipEmpty, returnvec[row][col], and movecolone step.hasNext(): callskipEmptyand return whetherrowis still insidevec.
Both methods call skipEmpty because either can come first, and hasNext may be called many times in a row; calling it again does nothing once (row, col) is on an element.
Complexity: O(1) amortized time per call, since each row is skipped once in total, and O(1) extra space.
class Vector2D:
def __init__(self, vec: List[List[int]]):
self.vec = vec
self.row = 0 # (row, col) is the position of the next element
self.col = 0
def next(self) -> int:
self._skip_empty()
value = self.vec[self.row][self.col]
self.col += 1
return value
def hasNext(self) -> bool:
self._skip_empty()
return self.row < len(self.vec)
def _skip_empty(self):
"""Move past the end of the current row and past empty rows."""
while self.row < len(self.vec) and self.col == len(self.vec[self.row]):
self.row += 1
self.col = 0