281 Zigzag Iterator

Given two 1d vectors, implement an iterator to return their elements alternately.

For example, given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].

Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question - Update (2015-09-18): The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:

[1,2,3]
[4,5,6,7]
[8,9]

It should return [1,4,8,2,5,9,3,6,7].

The Idea: Define two vector iterators and swap between them every next operation. The ending condition is when all (both) iterators have reached the end of their respected vectors.

Complexity: O(1) time for both operations, and constant space

class ZigzagIterator {
public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        iter1 = v1.begin();
        iter2 = v2.begin();
        end1 = v1.end();
        end2 = v2.end();
    }

    int next() {
        // need to define a priority
        if (iter1 == end1) {
            return *iter2++;
        }
        else if (iter2 == end2) {
            return *iter1++;
        }
        else if (is_v1) {
            is_v1 = !is_v1;
            return *iter1++;
        }
        else if (!is_v1) {
            is_v1 = !is_v1;
            return *iter2++;
        }
    }

    bool hasNext() {
        return !(iter1 == end1 && iter2 == end2);
    }

private:
    vector<int>::iterator iter1, iter2;
    vector<int>::iterator end1, end2;
    bool is_v1 = true;
};

/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/

Last updated