LeetCode 251, Medium. Topics: Design, Array, Two Pointers, Iterator. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:
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.
Examples
Constraints
0 <= vec.length <= 200
0 <= vec[i].length <= 500
-500 <= vec[i][j] <= 500
- At most
10^5 calls will be made to next and hasNext.
Follow up: As an added challenge, try to code it using only iterators in C++ or iterators in Java.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026