KatInterview

281. Zigzag Iterator

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core challenge of this problem is to design an iterator that can traverse two lists of integers, v1 and v2, in an alternating or "zigzag" fashion. This means fetching one element from v1, then one from v2, then the next from v1, the next from v2, and so on. A key requirement is to handle lists of unequal lengths correctly. If one list is exhausted, the iterator should seamlessly continue yielding elements from the other list until it too is exhausted. The design should also be considerate of the follow-up question, which asks how to extend the solution to k lists, suggesting that a scalable approach is preferred.

Solution

Zigzag Iterator in Python

from collections import deque

class ZigzagIterator:
    def __init__(self, v1: list[int], v2: list[int]):
        # Use a deque to store pairs of (vector, index).
        # This approach avoids modifying the original lists and works well
        # for Python's iterator model.
        self.queue = deque()
        
        # If v1 is not empty, add a pointer to its first element to the queue.
        if v1:
            self.queue.append([v1, 0])
        
        # If v2 is not empty, add a pointer to its first element to the queue.
        if v2:
            self.queue.append([v2, 0])

    def next(self) -> int:
        # Get the vector and current index from the front of the queue.
        vec, idx = self.queue.popleft()
        
        # Retrieve the element.
        result = vec[idx]
        
        # If there are more elements in this vector, add it back to the queue
        # with an incremented index.
        if idx + 1 < len(vec):
            self.queue.append([vec, idx + 1])
            
        return result

    def hasNext(self) -> bool:
        # If the queue is not empty, there are more elements to iterate.
        return bool(self.queue)

# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())

Zigzag Iterator in Java

public class ZigzagIterator {
    // A queue to hold iterators of the lists.
    private Queue<Iterator<Integer>> queue;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        // Initialize the queue.
        queue = new LinkedList<>();
        
        // If v1 is not empty, add its iterator to the queue.
        if (!v1.isEmpty()) {
            queue.add(v1.iterator());
        }
        
        // If v2 is not empty, add its iterator to the queue.
        if (!v2.isEmpty()) {
            queue.add(v2.iterator());
        }
    }

    public int next() {
        // Get an iterator from the front of the queue.
        Iterator<Integer> iter = queue.poll();
        
        // Get the next element from this iterator.
        int result = iter.next();
        
        // If this iterator still has more elements, add it back to the end of the queue.
        if (iter.hasNext()) {
            queue.add(iter);
        }
        
        return result;
    }

    public boolean hasNext() {
        // If the queue is not empty, it means there are still elements to be returned.
        return !queue.isEmpty();
    }
}

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i = new ZigzagIterator(v1, v2);
 * while (i.hasNext()) v[f()] = i.next();
 */

Zigzag Iterator in C++

class ZigzagIterator {
private:
    // A queue to store pairs of iterators. Each pair represents
    // the current position and the end of a vector.
    std::queue<std::pair<vector<int>::iterator, vector<int>::iterator>> q;

public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        // If v1 is not empty, push its begin and end iterators to the queue.
        if (!v1.empty()) {
            q.push({v1.begin(), v1.end()});
        }
        // If v2 is not empty, push its begin and end iterators to the queue.
        if (!v2.empty()) {
            q.push({v2.begin(), v2.end()});
        }
    }

    int next() {
        // Get the iterator pair from the front of the queue.
        auto it_pair = q.front();
        q.pop();

        // Dereference the current iterator to get the value.
        int result = *it_pair.first;

        // Move the current iterator to the next element.
        it_pair.first++;

        // If the iterator has not reached the end of the vector,
        // push it back to the queue for the next turn.
        if (it_pair.first != it_pair.second) {
            q.push(it_pair);
        }

        return result;
    }

    bool hasNext() {
        // If the queue is not empty, there are more elements to iterate.
        return !q.empty();
    }
};

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

Zigzag Iterator in TypeScript

class ZigzagIterator {
    // A queue to store tuples of [vector, index].
    private queue: Array<[number[], number]>;

    constructor(v1: number[], v2: number[]) {
        this.queue = [];

        // If v1 is not empty, add a reference to it and starting index 0 to the queue.
        if (v1.length > 0) {
            this.queue.push([v1, 0]);
        }

        // If v2 is not empty, add a reference to it and starting index 0 to the queue.
        if (v2.length > 0) {
            this.queue.push([v2, 0]);
        }
    }

    next(): number {
        // Dequeue the current vector and index pointer.
        const [vec, idx] = this.queue.shift()!;

        // Get the element.
        const result = vec[idx];

        // If the vector has more elements, enqueue it again with the next index.
        if (idx + 1 < vec.length) {
            this.queue.push([vec, idx + 1]);
        }

        return result;
    }

    hasNext(): boolean {
        // If the queue is not empty, there are more elements to iterate.
        return this.queue.length > 0;
    }
}

/**
 * Your ZigzagIterator will be instantiated and called as such:
 * var i = new ZigzagIterator(v1, v2), a = [];
 * while (i.hasNext()) a.push(i.next());
*/

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.