Grokking the Engineering Manager Coding Interview

0% completed

Zigzag Iterator (medium)

Problem Statement

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

Implement the Solution class:

  • Solution(List<int> v1, List<int> v2) is a constructor.
  • int next() returns the current element of the iterator and moves the iterator to the next element.
  • boolean hasNext() returns true if the iterator still has elements, and false otherwise.

Examples

Example 1

  • Input: V1 = [1,2], v2 = [3,4,5,6]
  • Expected Output: [1,3,2,4,5,6]
  • Explanation: The elements will be returned in [1,3,2,4,5,6] order when we make v1

.....

.....

.....

Like the course? Get enrolled and start learning!
Sandeep Gattani

Sandeep Gattani

· 3 years ago

What is the benefit of using Queue for this purpose and use additional space - instead of simply having reference of the 2 queues and switching between them?

Show 3 replies
S

Syed Ahmed

· 3 years ago

class Solution { private Queue<Integer> queueFirst; private Solution(){ queueFirst = new LinkedList<>(); } public Solution(List<Integer> v1, List<Integer> v2) { queueFirst = new LinkedList<>(); boolean toggle = true; int v1Index = 0; int v2Index = 0; while(!(v1Index==v1.size()) || !(v2Index==v2.size())){ if(!(v1Index==v1.size())){ queueFirst.add(v1.get(v1Index++)); } if(!(v2Index==v2.size())){ queueFirst.add(v2.get(v2Index++)); } } } public int next() { if(!queueFirst.isEmpty()){ return queueFirst.poll(); } return -1; } public boolean hasNext() { return !queueFirs
Show 1 reply
raol buqi

raol buqi

· 2 years ago

I think hasNext() in this case shouldn't just return true if there is an iterator in the queue, but it should also check if the iterator inside the queue hasNext()