Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Last active April 7, 2023 16:57
Show Gist options
  • Save optimistiks/96447a2b4c0ca84b28c153267397710b to your computer and use it in GitHub Desktop.
Save optimistiks/96447a2b4c0ca84b28c153267397710b to your computer and use it in GitHub Desktop.
Given m number of sorted lists in ascending order and an integer k, find the kth smallest number among all the given lists.
export function kSmallestNumber(lists, k) {
const heap = new MinHeap();
// initialize by pushing first element of each list into heap
for (let i = 0; i < lists.length; ++i) {
const list = lists[i];
if (list[0] != null) {
heap.offer([list[0], i, 0]);
}
}
// this is our last popped element
// since we pop elements from the heap in sorted order,
// after k pops, it will be our kth smallest element
let pop = 0;
// keep track of pops from heap, we need to do k pops to find kth smallest element
let count = 0;
while (count < k && heap.size() > 0) {
const [value, listIndex, elementIndex] = heap.poll();
pop = value;
count += 1;
// after pop, add the next element from the same list into the heap
const nextIndex = elementIndex + 1;
const nextValue = lists[listIndex][nextIndex];
if (nextValue != null) {
heap.offer([nextValue, listIndex, nextIndex]);
}
}
return pop;
}

image

Where m is how many lists we have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment