Skip to content

Algorithm

Merge Two Sorted Lists Algorithm

Two sorted lists. Combine them into one sorted list.

12 Mar 2024 · 2 min read

Merge Two Sorted Lists Algorithm

Two sorted lists. Combine them into one sorted list.

This is a fundamental building block. Merge sort uses it. Database joins use it. It's one of those problems that looks simple but teaches you a lot about pointer management.

The intuition

Walk through both lists at the same time. Compare the current elements. Pick the smaller one and move that pointer forward. Repeat until one list runs out, then tack on whatever's left.

The code (array version)

Javascript
const mergeSortedArrays = (arr1, arr2) => {
    const result = [];
    let i = 0;
    let j = 0;

    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] <= arr2[j]) {
            result.push(arr1[i++]);
        } else {
            result.push(arr2[j++]);
        }
    }

    while (i < arr1.length) result.push(arr1[i++]);
    while (j < arr2.length) result.push(arr2[j++]);

    return result;
};

mergeSortedArrays([2, 3, 8, 12], [4, 5, 9, 14]);
// [2, 3, 4, 5, 8, 9, 12, 14]

The code (linked list version)

For the classic LeetCode version with linked lists:

Javascript
var mergeTwoLists = function(list1, list2) {
    const dummy = { val: 0, next: null };
    let current = dummy;

    while (list1 && list2) {
        if (list1.val <= list2.val) {
            current.next = list1;
            list1 = list1.next;
        } else {
            current.next = list2;
            list2 = list2.next;
        }
        current = current.next;
    }

    current.next = list1 || list2;
    return dummy.next;
};

Complexity

  • Time: O(n + m) — each element is visited once.
  • Space: O(n + m) for the array version (new array), O(1) for the linked list version (rewiring existing nodes).

Trade-offs

The dummy node trick avoids special-casing the head of the merged list. A recursive solution is more elegant but uses O(n + m) stack space and risks stack overflow on very long lists. Iterative is safer for production.

Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.

Go further
Live cohort on Maven

Forward Deployed AI Engineering: From Customer Problem to Production Value

A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.

January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.

View the live cohort

Keep reading