Skip to the solution
EasyDSA4 min read

How do you merge two sorted linked lists?

839 views

The problem

Question presented to candidate: "You are given the heads of two linked lists, each already sorted in ascending order. Merge them into one sorted list by splicing the existing nodes together, and return its head. Please write it in Python."

What a strong answer should cover:

  • The idea: the smallest remaining value is always at the front of one of the two lists, so repeatedly take the smaller front node.
  • A dummy (sentinel) node and a tail pointer, which remove the special case for the first node.
  • Attaching the leftover list in one step when the other runs out.
  • O(m + n) time and O(1) extra space for the loop; the recursive version uses O(m + n) stack.
  • Stability: using <= so equal values keep list a first.
  • Python specifics: is None checks, <= for stability, why heapq.merge does not apply to node objects, and the recursion limit for the recursive version.

Clarifying questions expected:

  • "Can I reuse the input nodes, or must the original lists stay intact?"
  • "Are there duplicates, and if so should ties come from the first list?"

Code / implementation expected: Yes โ€” a Python merge_two_lists(a, b) with a dummy node, plus the recursive version if time allows.

  • 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

4 min read ยท 11 sections

Python code

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

PythonDummy-node merge on normal and edge-case inputs
PythonStability, the recursive version, and counting comparisons

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 13 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 nextEasy

How do you add one to a number represented as a digit array?

Continue