How is this code working?
public static int findKthSmallest(List<Integer[]> lists, int k) {
PriorityQueue<Node> minHeap = new PriorityQueue<Node>(
(n1, n2) -> lists.get(n1.arrayIndex)[n1.elementIndex] - lists.get(n2.arrayIndex)[n2.elementIndex]);
// put the 1st element of each array in the min heap
for (int i = 0; i < lists.size(); i++)
if (lists.get(i) != null)
minHeap.add(new Node(0, i));
// take the smallest (top) element form the min heap, if the running count is equal to k return the number
// if the array of the top element has more elements, add the next element to the heap
int numberCount = 0, result = 0;
while (!minHeap.isEmpty()) {
Node node = minHeap.poll();
result = lists.get(node.arrayIndex)[node.elementIndex];
if (++numberCount == k)
break;
node.elementIndex++;
if (lists.get(node.arrayIndex).length > node.elementIndex)
minHeap.add(node);
}
return result;
}
I am not getting this part of node.elementindex
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Kth Smallest Number in M Sorted Lists (Medium) - Grokking the Coding Interview: Patterns for Coding Questions