L3 · FAANGHeaps & streams~15 min · 5 tests

Merge K Sorted Lists With a Heap

Merge k sorted lists into one in O(N log k) with heapq, always popping the smallest head. Compare with concatenate-and-sort and pairwise merging.

The problem

lists contains k lists, each sorted ascending. Return one sorted list with every value. Use a heap so the cost is O(N log k), where N is the total number of values.

Examples

  1. Example 1

    Input

    merge_k([[1, 4, 5], [1, 3, 4], [2, 6]])

    Expected output

    [1, 1, 2, 3, 4, 4, 5, 6]
  2. Example 2

    Input

    merge_k([[], [1]])

    Expected output

    [1]

+ 3 hidden tests on Submit.

Edge cases to ask about

  • Empty lists
  • k = 0
  • Duplicates across lists

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · merge_k
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Concatenate and sortO(N log N)O(N)Ignores that each list is sorted.
    Merge one list at a timeO(N · k)O(N)
    bestMin-heap of the k headsO(N log k)O(k)The heap never holds more than k entries.
    Walkthrough of the optimal approach (try it yourself first)

    Push the first element of each list onto a min-heap as (value, list_index, position). Pop the smallest, append it, and push the next element from the same list. The heap never holds more than k items, so each of the N operations costs O(log k).

    Including list_index in the tuple breaks ties and avoids comparing linked-list nodes (in the LeetCode version). heapq.merge(*lists) is the standard-library answer.

    Complexity: O(N log k) time, O(k) space. Each of the N values is pushed and popped once on a heap that never exceeds k entries.

    Reveal the reference solution
    import heapq
    
    def merge_k(lists):
        heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
        heapq.heapify(heap)
        out = []
        while heap:
            value, i, j = heapq.heappop(heap)
            out.append(value)
            if j + 1 < len(lists[i]):
                heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
        return out

    The brute force, for comparison

    def merge_k(lists):
        return sorted(x for lst in lists for x in lst)

    Follow-ups interviewers ask

    • Linked-list version.
    • Divide and conquer pairwise merge — same O(N log k).

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Merge K Sorted Lists With a Heap in Python?

    The optimal solution runs in O(N log k) time and O(k) auxiliary space. Each of the N values is pushed and popped once on a heap that never exceeds k entries.

    What is the brute-force approach, and how do you optimise it?

    Concatenate and sort: O(N log N) time, O(N) space. Ignores that each list is sorted. Merge one list at a time: O(N · k) time, O(N) space. Min-heap of the k heads: O(N log k) time, O(k) space. The heap never holds more than k entries.

    What follow-up questions do interviewers ask about Merge K Sorted Lists With a Heap?

    Linked-list version. Divide and conquer pairwise merge — same O(N log k).