I found the following interview question here.
SortedIterator - consists of List of Lists with sorted int values in each list. You have to give next sorted value when call next().
have to implement methods * constructor * next() * hasNext()
[ [1, 4, 5, 8, 9], [3, 4, 4, 6], [0, 2, 8] ]
next() -> 0, 1, 2, 3, 4, 4, 4...
I wrote a quick implementation in Java:
package com.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class SortedIterator implements Iterator<Integer> {
private final List<Integer> mFlattenedList;
private final Iterator<Integer> mIntegerIterator;
SortedIterator(final List<List<Integer>> lists) {
mFlattenedList = flattenLists(lists);
mIntegerIterator = mFlattenedList.iterator();
}
private List<Integer> flattenLists(final List<List<Integer>> lists) {
final List<Integer> result = new ArrayList<>();
for (List<Integer> list : lists) {
for (int value : list) {
result.add(value);
}
}
Collections.sort(result);
return result;
}
@Override
public boolean hasNext() {
return mIntegerIterator.hasNext();
}
@Override
public Integer next() {
return mIntegerIterator.next();
}
}
Time: O (K * N) to flatten the input list of lists + O (N*K) to iterate over the flattened list = O (N * K)
Space: O (N * K) to store the flattened list.
N - number of lists.
K - number of elements in each list.
But the answer from the link says:
There is a solution with time complexity O(logN) using a priority queue. Maybe an interviewer expected something like that, I don't know.
How is O (log N) possible? If a priority queue is used, every time we call hasNext(), we'll need to check if the queue is empty (O(1)). Then we call next() which extracts the min element from the queue (O(log (N*K)) for any implementation) according to the table. Since we need to call next() N * K times, it takes us O(N * K * log (N*K) to iterate over all the elements.