How do you merge k sorted lists efficiently?
LeetCode Patterns Flashcards: Heap and Priority Queue, Top K, Merge K Sorted
Аудио-карточка · 0:31Nortren·
How do you merge k sorted lists efficiently?
0:31
Insert the first element from each of the k lists into a min-heap, along with which list it came from and its position. Repeatedly extract the minimum from the heap, add it to the result, and insert the next element from the same list if one exists. This runs in O of n log k time where n is the total number of elements across all lists, because each of the n elements is inserted and extracted from a heap of size at most k. This is more efficient than merging two lists at a time, which would take O of n times k total time. The heap always gives you the globally smallest unprocessed element.
neetcode.io