Interview Question for Java Developers

Country: United States
Interview Type: Phone Interview

Comment hidden because of low score. Click to expand.
of 2 vote

This can be done, by maintaining a min heap of elements and its associated iterator index in a struct.
hasNext - returns if there are any elements in min heap
next fetches the top element in minheap , and then grabs its iterator and checks if it has any element if so add it to the minheap.

private class minHeapElement {
int index;
int value;
PriorityQueue<minHeapElement> minHeap = new PriorityQueue(iters.size(), (a,b)-> a.value-b.value );

- Anonymous March 21, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
of 1 vote

This is just "merge k sorted arrays". Use merge sort.

- Basmati March 21, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
of 0 vote

Use a priority queue and insert elements into the queue as you go along and call next. Posting my solution below in Python:

from queue import PriorityQueue

class SuperIterator:
  def __init__(self, iterators):
    self.sortedQueue = PriorityQueue()
    for iterator in iterators:
      self.sortedQueue.put((next(iterator), iterator))

  def hasNext(self):
    return self.sortedQueue.qsize() != 0

  def next(self):
    value, iterator = self.sortedQueue.get()
      next_value = next(iterator)
      self.sortedQueue.put((next_value, iterator))
    except StopIteration:
    return value

Test code:

# Test code
# Example 1
list1 = [1, 4, 5,20]
list2 = [2,10,12,50]
s = SuperIterator([iter(list1), iter(list2)])
while s.hasNext():
  print(, end=', ')
# Output: 1, 2, 4, 5, 10, 12, 20, 50,

# Example 2
list1 = [12,14,16]
list2 = [4,7,9,50,100]
list3 = [6,8,10,13]
s = SuperIterator([iter(list1), iter(list2), iter(list3)])
while s.hasNext():
  print(, end=', ')
# Output: 4, 6, 7, 8, 9, 10, 12, 13, 14, 16, 50, 100,

- prudent_programmer March 22, 2018 | Flag Reply

Add a Comment

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.


is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More


CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More