251. Flatten 2D Vector

Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

Example:

Vector2D iterator = new Vector2D([[1,2],[3],[4]]);

iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false

Notes:

  1. Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see herearrow-up-right for more details.

  2. You may assume that next() call will always be valid, that is, there will be at least a next element in the 2d vector when next() is called.

Follow up:

As an added challenge, try to code it using only iterators in C++arrow-up-right or iterators in Javaarrow-up-right.

class Vector2D {
public:
    // queue, time: O(n); space: O(n)
    Vector2D(vector<vector<int>> v) {
        for (vector<int>& a : v) {
            for (int num : a) {
                q.push(num);
            }
        }
    }
    
    int next() {
        int t = q.front(); q.pop();
        return t;
    }
    
    bool hasNext() {
        return !q.empty();
    }
    queue<int> q;
};

Last updated