Leetcode #251: Flatten 2D Vector
In this guide, we solve Leetcode #251 Flatten 2D Vector in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Design, Array, Two Pointers, Iterator
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
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
Python Solution
class Vector2D:
def __init__(self, vec: List[List[int]]):
self.i = 0
self.j = 0
self.vec = vec
def next(self) -> int:
self.forward()
ans = self.vec[self.i][self.j]
self.j += 1
return ans
def hasNext(self) -> bool:
self.forward()
return self.i < len(self.vec)
def forward(self):
while self.i < len(self.vec) and self.j >= len(self.vec[self.i]):
self.i += 1
self.j = 0
# Your Vector2D object will be instantiated and called as such:
# obj = Vector2D(vec)
# param_1 = obj.next()
# param_2 = obj.hasNext()
Complexity
The time complexity is O(n) (after optional sort O(n log n)). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.