Neural Mastery
← Back to Practice

Merge K Sorted Lists

Difficulty: Hard · Pattern: K-Way Merge · Concept: Algorithms & Data Structures — Core Data Structures

Given k already-sorted lists, merge them into a single sorted list containing every element.

Merging two sorted lists is a familiar O(n)O(n) operation. The naive extension to kk lists — concatenate everything and call sorted() — costs O(NlogN)O(N \log N) over all NN total elements, throwing away the fact that each individual list was already sorted. The k-way merge pattern does better: keep a min-heap holding just the current smallest unconsumed element from each of the kk lists. Repeatedly pop the overall smallest, then push in the next element from whichever list it came from — the same heap/priority-queue idea beam search uses to track the top-kk candidates efficiently.

Your task: implement merge_k_sorted(lists) in O(Nlogk)O(N \log k) time using Python's heapq, where lists is a list of kk sorted lists (each may be empty).

Implement it yourself
assert merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]) == [1, 1, 2, 3, 4, 4, 5, 6] assert merge_k_sorted([[], []]) == [] assert merge_k_sorted([[1, 2, 3]]) == [1, 2, 3] assert merge_k_sorted([[5], [1], [3], [2], [4]]) == [1, 2, 3, 4, 5] assert merge_k_sorted([[-3, -1, 2], [-2, 0, 5]]) == [-3, -2, -1, 0, 2, 5]

Next: Smallest Range Covering Elements from K Lists (a harder K-way-merge problem), or continue to Shortest Path in an Unweighted Graph

Last updated Sep 5, 2026Edit this pageReport an issue