Skip to the solution
HardDSA12 min read

How do you merge k sorted lists?

1.1k views

The problem

Question presented to candidate: "You are given k sorted singly linked lists. Merge them into one sorted linked list and return its head. Write it in Python, and tell me the time and space complexity in terms of k and the total number of nodes N."

What a strong answer should cover:

  • The baseline approaches and their costs: collect-and-sort O(N log N); merging one by one O(Nยทk).
  • The min-heap of the k current heads: pop the smallest, append it, push its next; O(N log k) time, O(k) extra space, nodes re-linked rather than copied.
  • Divide and conquer (pairwise merging in log k rounds) as the other O(N log k) answer, and when each is preferable.
  • Edge cases: empty input, empty lists inside the input, duplicates, one list.
  • Python specifics: heapq compares whole tuples, and ListNode objects are not comparable โ€” push (node.val, i, node) with a unique tie-breaker i, or define __lt__; use a dummy head node.

Clarifying questions expected:

  • May I re-use the existing nodes, and can lists be empty?
  • How large are k and N, and are the lists in memory or streamed?

Code / implementation expected: Yes โ€” a full heapq-based merge on a ListNode class in Python.

  • heap
  • linked-list

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMerge k sorted linked lists with a min-heap of the current heads
PythonOne by one vs divide and conquer vs heap: comparisons and heap size counted

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 131 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Minimum window substring: how does the sliding window with need/have counters work?

Continue