Skip to the solution
MediumDSA9 min read

Merge k sorted lists: heap vs divide-and-conquer — which is better for n=10k?

281 views

The problem

Question presented to candidate: "You have k sorted Python lists holding about 10,000 numbers in total. Would you merge them with a heap or with divide and conquer? Code both, tell me their complexity, and tell me which one you would actually ship."

What a strong answer should cover:

  • Both are O(N log k) time; sequential merging is O(N·k) and is the trap to avoid.
  • Heap: O(k) extra memory, works on streams, can stop early; divide and conquer: fewer comparisons (one per item per level) and no heap at all.
  • Clarifying what "n = 10k" means: total items N, or number of lists k.
  • Python details: heapq is a min-heap on a plain list; entries must be tuples with a tie-breaker index so Python never compares the payload; heapq.merge already exists in the standard library.
  • An honest measurement: at this size in CPython the C-implemented heapq beats a pure-Python merge loop, and sorted() beats both.

Clarifying questions expected:

  • Is 10,000 the total item count or the number of lists?
  • Arrays or linked lists; all in memory or streams?

Code / implementation expected: Yes — a heapq-based k-way merge and a recursive pairwise merge, in Python 3.

  • heap
  • linked list
  • Google

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

9 min read · 15 sections

Python code

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

PythonHeap and divide-and-conquer merges on six inputs
PythonComparison counts: sequential vs heap vs divide, N = 10000

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 105 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 nextMedium

What is backtracking?

Continue