Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Linked List

Merge Two Sorted Lists

EASY✓ CHIP-TIMEDLC #21 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Weave two already-sorted linked lists into one sorted list, reusing the existing nodes instead of allocating new ones.

Two singly linked lists arrive, each already sorted in non-decreasing order on its own, and the job is to weave them into a single sorted list.

The existing nodes should be reused and rewired rather than copied into fresh ones — the merge is a matter of redirecting pointers, not rebuilding values from scratch.

Either list can be empty, in which case the other list is simply handed back untouched as the answer, and ties between equal values can be resolved in either order.

  • each list holds up to a few thousand nodes
  • both input lists are individually sorted in non-decreasing order
  • either list, or both, may be empty
  • existing nodes are relinked, not copied into new ones
EX 01
list1 = [1, 3, 5] · list2 = [2, 4, 6]
→ [1, 2, 3, 4, 5, 6]
perfect interleave
EX 02
list1 = [] · list2 = []
→ []
EX 03
list1 = [] · list2 = [0]
→ [0]

The hintstake only what you need

HINT 1 THE NUDGE

Both lists are sorted — so the next node of the answer is always one of just two candidates.

HINT 2 THE STRUCTURE

A dummy head node kills every special case about starting the result.

HINT 3 ONE STEP FROM THE ANSWER

Advance whichever list offered the smaller head; when one runs out, the other attaches whole — no node-by-node copying of the tail.

Coach's boardthe pattern, step by step

THE DUMMY-HEAD WEAVEPATTERN · DUMMY-HEAD WEAVElist1 = 1 → 3 → 5 · list2 = 2 → 4 → 6
1
3
5
2
4
6
STEP 1

Two sorted lists: 1→3→5 and 2→4→6. Splice a dummy-head result by always taking the smaller of the two current heads.

STEP 1 / 8 · ← → WORK TOO

The splitstwo paces, two languages

grind/merge-two-sorted-lists.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()
        tail = dummy
        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        tail.next = list1 if list1 else list2
        return dummy.next
TIME O(M+N)SPACE O(1)PYTHON · RACE PACE · 14 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED