AlgoTales · Roadmap

Merge two sorted lists

Beginner · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Merging two sorted lists means producing one sorted list by always taking the smaller of the two front items. Because each list is already in order, you never look back, and one pass over both is enough.

Practical use cases

  • Web app: Combining two servers' log files by time. A site runs on two servers, and each writes its own log sorted by time. To see what happened across the whole system, you compare the next line of each file and output the earlier one. In one pass you get a single timeline, even for files with millions of lines.
  • Web app: One order history from two sources. A customer page shows orders from the old shop database and from the new one, each already sorted newest first. Instead of loading both and sorting again, the code merges them as it renders. The page shows a combined, correctly ordered history right away.
  • System: Merge sort and database merges. Merge sort splits data, sorts the small pieces, and then merges them back, so this step is its heart. Databases and search engines also merge sorted results from several sources, such as index files, in the same way, so a query touching several files still returns one tidy ordered answer.

The story: Two Queues, One Ticket Window

At the railway station two ticket counters closed for lunch and only one window stayed open. The two queues had to join, but both were already arranged by token number: Queue A had 1, 4, 7 and Queue B had 2, 3, 8. The guard wanted one long queue in token order, with nobody asking people to run around.

He used the zipper rule. "Look at the two people at the front. Whoever has the smaller token goes next into the new queue. Repeat." Token 1 went, then 2, then 3, then 4, then 7. After A's tokens were used up, B's remaining token 8 simply followed, because B was already in order. No more comparing was needed.

The guard also kept a small stool as a "starting point" for the new queue, a dummy. It let him attach the very first person the same way as everybody else, without making a special case for "the new queue is empty".

That is merging two sorted linked lists. You re-use the existing nodes, just changing their next arrows, so no extra memory is needed for new nodes. It is the heart of merge sort, which you will meet in a couple of lessons.

How to spot this problem, and where you need it

You have two collections that are each already in order and need one combined ordered result, and re-sorting everything from scratch wastes the work already done.

Signs you need it

  • Two feeds, logs, result sets or API pages come back already sorted by the same field, such as time or price.
  • You append both lists together and call sort(), even though each part was ordered already.
  • The problem says "merge two sorted lists/arrays" or is a sub-step of a larger merge-sort style solution.

Where to use it in a project

  • Combining sorted logs, events or transactions from several servers or microservices.
  • Joining sorted result pages from two data sources before showing them.
  • The merge step of merge sort when sorting large data.

The solution

Keep a pointer at the front of each list and an output list that starts empty. Compare the two front items, move the smaller one to the output and advance that list's pointer. Repeat until one list runs out, then attach the rest of the other list as it is, since it is already in order. Each item is looked at only once.

Payoff: Before: concatenating and re-sorting 2 million log lines. After: one pass over the 2 million lines, no sorting needed.

Explain it like I am 8

Two lines of kids are already in height order. Look at the first kid in each line and let the shorter one step into a new line. Keep doing that. When one line is finished, the rest of the other line just walks in behind.

How it works, step by step

  1. Make a dummy node and a tail pointer that starts on it.
  2. Compare the front nodes of A and B. Attach the smaller one to tail.next, move that list forward, and move tail onto the attached node.
  3. Repeat until one list is empty.
  4. Hang the remaining list (it is already sorted) onto tail.next.
  5. Return dummy.next, the head of the merged list.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}
function fromArray(array $vals): ?Node {
    $head = null;
    foreach (array_reverse($vals) as $v) { $head = new Node($v, $head); }
    return $head;
}
function show(?Node $head): string {
    $out = [];
    for ($c = $head; $c !== null; $c = $c->next) $out[] = $c->val;
    return implode(' -> ', $out);
}

function mergeSorted(?Node $a, ?Node $b): ?Node {
    $dummy = new Node(0);              // a stool to start from
    $tail = $dummy;
    while ($a !== null && $b !== null) {
        if ($a->val <= $b->val) {      // <= keeps equal items in their original order
            $tail->next = $a;
            $a = $a->next;
        } else {
            $tail->next = $b;
            $b = $b->next;
        }
        $tail = $tail->next;
    }
    $tail->next = $a !== null ? $a : $b;   // hang whatever is left
    return $dummy->next;
}

$merged = mergeSorted(fromArray([1, 4, 7]), fromArray([2, 3, 8]));
echo show($merged) . "\n";                                  // 1 -> 2 -> 3 -> 4 -> 7 -> 8
echo show(mergeSorted(fromArray([]), fromArray([5, 6]))) . "\n";   // 5 -> 6

JavaScript

class Node {
  constructor(val, next = null) { this.val = val; this.next = next; }
}
function fromArray(vals) {
  let head = null;
  for (let i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
  return head;
}
function show(head) {
  const out = [];
  for (let c = head; c !== null; c = c.next) out.push(c.val);
  return out.join(' -> ');
}

function mergeSorted(a, b) {
  const dummy = new Node(0);          // a stool to start from
  let tail = dummy;
  while (a !== null && b !== null) {
    if (a.val <= b.val) {             // <= keeps equal items in their original order
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }
    tail = tail.next;
  }
  tail.next = a !== null ? a : b;     // hang whatever is left
  return dummy.next;
}

const merged = mergeSorted(fromArray([1, 4, 7]), fromArray([2, 3, 8]));
console.log(show(merged));                                   // 1 -> 2 -> 3 -> 4 -> 7 -> 8
console.log(show(mergeSorted(fromArray([]), fromArray([5, 6]))));   // 5 -> 6

Java

import java.util.*;

public class Main {
    static class Node {
        int val;
        Node next;
        Node(int val, Node next) { this.val = val; this.next = next; }
    }

    static Node fromArray(int... vals) {
        Node head = null;
        for (int i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
        return head;
    }

    static String show(Node head) {
        StringJoiner out = new StringJoiner(" -> ");
        for (Node c = head; c != null; c = c.next) out.add(String.valueOf(c.val));
        return out.toString();
    }

    static Node mergeSorted(Node a, Node b) {
        Node dummy = new Node(0, null);    // a stool to start from
        Node tail = dummy;
        while (a != null && b != null) {
            if (a.val <= b.val) {          // <= keeps equal items in their original order
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;   // hang whatever is left
        return dummy.next;
    }

    public static void main(String[] args) {
        Node merged = mergeSorted(fromArray(1, 4, 7), fromArray(2, 3, 8));
        System.out.println(show(merged));                                      // 1 -> 2 -> 3 -> 4 -> 7 -> 8
        System.out.println(show(mergeSorted(fromArray(), fromArray(5, 6))));   // 5 -> 6
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type Node struct {
	val  int
	next *Node
}

func fromSlice(vals []int) *Node {
	var head *Node
	for i := len(vals) - 1; i >= 0; i-- {
		head = &Node{val: vals[i], next: head}
	}
	return head
}

func show(head *Node) string {
	var out []string
	for c := head; c != nil; c = c.next {
		out = append(out, fmt.Sprint(c.val))
	}
	return strings.Join(out, " -> ")
}

func mergeSorted(a, b *Node) *Node {
	dummy := &Node{} // a stool to start from
	tail := dummy
	for a != nil && b != nil {
		if a.val <= b.val { // <= keeps equal items in their original order
			tail.next = a
			a = a.next
		} else {
			tail.next = b
			b = b.next
		}
		tail = tail.next
	}
	if a != nil { // hang whatever is left
		tail.next = a
	} else {
		tail.next = b
	}
	return dummy.next
}

func main() {
	merged := mergeSorted(fromSlice([]int{1, 4, 7}), fromSlice([]int{2, 3, 8}))
	fmt.Println(show(merged))                                              // 1 -> 2 -> 3 -> 4 -> 7 -> 8
	fmt.Println(show(mergeSorted(fromSlice(nil), fromSlice([]int{5, 6})))) // 5 -> 6
}

Time: O(n + m) · Extra space: O(1). Every node is attached exactly once, and we reuse the existing nodes instead of copying them.

Watch out for

  • Forgetting to attach the leftover list after the loop. The tail of the longer list gets lost.
  • No dummy node: you end up writing special code for the very first node.
  • Building new nodes for every value. It works, but wastes memory; relinking the existing nodes is the point.

Quick check

  1. At each step, which node do we attach to the merged list?
    • The larger of the two fronts
    • The smaller of the two fronts
    • Always from list A
    • A random one
  2. One list is finished and the other still has nodes. What now?
    • Sort the rest again
    • Throw the rest away
    • Hang the rest on directly, since it is already sorted
    • Compare each with null
  3. Time to merge lists of sizes n and m?
    • O(n × m)
    • O(log n)
    • O(n²)
    • O(n + m)