Flatten 2D Vector
Problem
Design an iterator over a 2D vector. Support next() and hasNext().
vec = [[1,2],[3],[4]][1,2,3,4]class Vector2D:
def __init__(self, vec):
self.vec = vec
self.r = 0
self.c = 0
def _advance(self):
while self.r < len(self.vec) and self.c >= len(self.vec[self.r]):
self.r += 1
self.c = 0
def next(self):
self._advance()
v = self.vec[self.r][self.c]
self.c += 1
return v
def hasNext(self):
self._advance()
return self.r < len(self.vec)
class Vector2D {
constructor(vec) { this.vec = vec; this.r = 0; this.c = 0; }
_advance() {
while (this.r < this.vec.length && this.c >= this.vec[this.r].length) {
this.r++; this.c = 0;
}
}
next() {
this._advance();
const v = this.vec[this.r][this.c]; this.c++;
return v;
}
hasNext() { this._advance(); return this.r < this.vec.length; }
}
class Vector2D {
int[][] vec; int r = 0, c = 0;
public Vector2D(int[][] v) { vec = v; }
void advance() {
while (r < vec.length && c >= vec[r].length) { r++; c = 0; }
}
public int next() { advance(); return vec[r][c++]; }
public boolean hasNext() { advance(); return r < vec.length; }
}
class Vector2D {
vector> v; int r = 0, c = 0;
void advance() { while (r < (int)v.size() && c >= (int)v[r].size()) { r++; c = 0; } }
public:
Vector2D(vector>& vec) : v(vec) {}
int next() { advance(); return v[r][c++]; }
bool hasNext() { advance(); return r < (int)v.size(); }
};
Explanation
We need an iterator that walks a list of lists as if it were one flat list. The simplest reliable way is to keep two cursors: r for the current row and c for the column inside that row.
The heart of the design is the _advance helper. It moves the cursor forward past any position that has run off the end of its row — including empty rows, which it skips entirely. After _advance, the cursor either points at a real element or has gone past the last row.
hasNext() calls _advance and then just checks whether a valid row remains. next() also calls _advance, reads the element at (r, c), steps c forward, and returns the value.
Calling _advance from both methods is what keeps things correct even when rows are empty or callers mix hasNext() and next() in any order.
Example: for [[1,2],[],[3],[],[4]] the cursor yields 1 and 2, then _advance jumps over the empty row to reach 3, and so on, producing 1, 2, 3, 4.