251 Flatten 2D Vector
Implement an iterator to flatten a 2d vector.
For example, Given 2d vector =
By callingnextrepeatedly untilhasNextreturns false, the order of elements returned bynextshould be:[1,2,3,4,5,6]
.
Follow up: As an added challenge, try to code it using only iterators in C++ or iterators in Java.
The Idea: Maintain a row and column pointer, and update these for each next()
call. The row will increments as the column will reset to 0, when the column index is going to exceed it's current row vector. One challenge was dealing with empty vectors {}
. These need to be ignored and iterated over every time we enter the start of a new row.
Complexity: O(n) time where n is the total number of elements in the vector.
Last updated