Merge Two Sorted Lists solution explained

To merge two sorted linked lists, put a placeholder node in front of the result and keep a tail pointer; repeatedly attach whichever list's current node has the smaller value, advance that list, and when one list runs out, attach the rest of the other. The Merge Two Sorted Lists solution reuses the existing nodes and runs in O(m + n) time with O(1) extra space.

By Published 8 min read

What needs to happen

You are given the first nodes of two singly linked lists. Each list is already in non-decreasing order, and either may be empty. Produce a single list in non-decreasing order that contains every node from both, and return its first node. The usual expectation is that you relink the nodes you were given rather than allocate new ones.

Examples invented for this walkthrough
First listSecond listMerged
1 → 4 → 92 → 3 → 101 → 2 → 3 → 4 → 9 → 10
(empty)5 → 65 → 6
2 → 222 → 2 → 2
-3 → 0-7 → 8-7 → -3 → 0 → 8
Examples invented for this walkthrough. Scroll sideways on a small screen.

Questions worth a few seconds: may the input lists be modified, or must they stay intact? When two values are equal, does it matter which node comes first? Are values sorted ascending or descending? The tie question sounds pedantic, but stable merging is exactly what merge sort depends on, so it can come up as a follow-up.

Why this is a staple

Merging is the core step of merge sort and of many systems tasks, such as combining sorted log files or sorted result pages from several shards. In an interview, the problem checks two practical skills: keeping track of a growing list without special-casing the first node, and finishing cleanly when one input runs out. The dummy-node technique solves the first, and a single assignment solves the second. Candidates who skip the dummy usually end up with a tangle of if statements around the head.

Where interviewers take it next

  • Write it recursively. The smaller front node becomes the head, and its next is the merge of everything that remains. Clean to read, but the depth equals the combined length.
  • Merge k sorted lists. Keep a min-heap holding the front node of each list; pop the smallest, attach it, and push its successor. That is O(N log k) for N nodes in total. Pairwise merging in rounds, like merge sort, gives the same bound. Code for the heap version is below.
  • Sort a whole linked list. Split it at the middle with slow and fast pointers, sort each half recursively, and merge them with this routine, for O(n log n).
  • Drop duplicates while merging. Before attaching a node, skip it if its value equals the tail's value.
  • Arrays instead of lists. When the first array has spare room at its end, fill from the back so nothing is overwritten before it is read.

Simple approach: collect, sort, rebuild

Copy every value from both lists into one array, sort it, and build a fresh list. It is correct and short, but it ignores the fact that both inputs are already sorted, costs O((m + n) log(m + n)) time and O(m + n) memory, and creates new nodes. Mention it to show the baseline, then improve on it.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def merge_by_sorting(a, b):
    vals = []
    for node in (a, b):
        while node:
            vals.append(node.val)
            node = node.next
    head = None
    for v in sorted(vals, reverse=True):
        head = ListNode(v, head)
    return head
Node class used below, plus the collect-and-sort baseline.

Optimal approach: splice behind a dummy head

Create one throwaway node called the dummy and a pointer called tail that starts on it. While both lists still have nodes, compare their front values, attach the smaller node after tail, advance the list it came from, and move tail onto the node you just attached. When either list empties, the other one is already sorted and every value in it is at least as large as anything attached so far, so a single assignment hooks the whole remainder on. Return dummy.next.

Using <= when comparing means that on a tie the node from the first list goes first. That keeps the merge stable, which is the property merge sort needs to preserve the original order of equal keys.

def merge_sorted(a, b):
    dummy = ListNode()
    tail = dummy
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a if a else b  # one list is done; attach the other
    return dummy.next
Python: iterative merge, O(m + n) time and O(1) extra space.
class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function mergeSorted(a, b) {
  const dummy = new ListNode();
  let tail = dummy;
  while (a !== null && b !== null) {
    if (a.val <= b.val) {
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }
    tail = tail.next;
  }
  tail.next = a !== null ? a : b;
  return dummy.next;
}
JavaScript: the same splice with a small node class.
def merge_sorted_recursive(a, b):
    if a is None:
        return b
    if b is None:
        return a
    if a.val <= b.val:
        a.next = merge_sorted_recursive(a.next, b)
        return a
    b.next = merge_sorted_recursive(a, b.next)
    return b
Recursive version: neat, but one stack frame per attached node.
import heapq
import itertools


def merge_many(heads):
    order = itertools.count()
    heap = [(h.val, next(order), h) for h in heads if h]
    heapq.heapify(heap)
    dummy = ListNode()
    tail = dummy
    while heap:
        _, _, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, next(order), node.next))
    tail.next = None
    return dummy.next
Follow-up: merge k sorted lists with a heap. The counter breaks ties so nodes are never compared.

The middle element of each heap entry matters. Without it, two entries with equal values would make Python compare the node objects themselves, which raises a TypeError. A running counter guarantees every tuple differs before the comparison ever reaches the node.

Complexity

m and n are the two list lengths; N is the total over k lists
ApproachTimeExtra spaceNotes
Collect, sort, rebuildO((m + n) log(m + n))O(m + n)Ignores the existing order and allocates nodes
Dummy head and tail, iterativeO(m + n)O(1)The expected answer
Recursive mergeO(m + n)O(m + n) call stackShort, but deep on long lists
k lists with a min-heapO(N log k)O(k)The standard follow-up
m and n are the two list lengths; N is the total over k lists. Scroll sideways on a small screen.

Edge cases

  • Both lists empty: return nothing.
  • One list empty: return the other unchanged.
  • Every value in one list is smaller than every value in the other, so the loop ends early and the remainder attachment does most of the work.
  • Many equal values across both lists, which checks the tie rule.
  • Negative numbers mixed with positive ones.
  • Very long inputs with the recursive version, which can exceed the recursion limit.

Errors that come up a lot

  • Forgetting to attach the leftover list after the loop, which silently drops nodes.
  • Not moving tail forward after attaching, so every new node overwrites the previous link.
  • Special-casing the head with nested ifs instead of using a dummy, which leads to bugs on empty inputs.
  • Returning the dummy itself rather than the node after it.
  • In the k-list heap, pushing raw nodes or tuples without a tie-breaker, which fails when two values are equal.

How to explain it out loud

Fictional example

Narrating the merge without losing the listener
Candidate
Both inputs are already sorted, so I only ever need to compare their front nodes. I start with a dummy node and a tail pointer so the head is not a special case.
Candidate
Each step I attach the smaller front node to tail and advance that list. Once one list is empty, I attach the other one whole, since it is sorted and everything left in it is large enough.
Candidate
That is linear in the total length with constant extra space. For 1, 4, 9 and 2, 3, 10 I take 1, 2, 3, 4, 9, then the first list is empty and 10 is attached.

Next problems to try

Reverse Linked List practices the same careful relinking with a different goal, and Linked List Cycle teaches the slow and fast pointers you need to split a list for merge sort. The merge idea on intervals rather than nodes appears in Merge Intervals, and the heap from the k-list follow-up is the same one used in Top K Frequent Elements. The full set lives on the coding problems hub.

How Natively fits into practice

When you are drilling list problems, Natively can read the question from a screenshot on your Mac or Windows computer and suggest the dummy-node approach and code, which you can hold up against your own after you have tried. Because it transcribes mock interviews, you can also go back and see whether you mentioned the leftover attachment and the tie rule while you talked. More on an AI interview assistant.

Questions people ask

How do you merge two sorted linked lists?

Start a dummy node with a tail pointer on it. While both lists have nodes, attach the smaller front node to tail and advance that list. When one list is empty, attach the rest of the other and return the node after the dummy.

What is the time complexity of merging two sorted lists?

O(m + n), since each node is attached once. The iterative version uses O(1) extra space; the recursive version uses O(m + n) call stack.

Why use a dummy node?

It gives the result a fixed starting point, so attaching the very first node is no different from attaching any other. Without it you need separate code for the head and for empty inputs.

How do you merge k sorted lists?

Put the front node of each list in a min-heap, repeatedly pop the smallest, attach it, and push its successor. That is O(N log k) for N nodes in total. Merging pairs in rounds gives the same bound.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP