◀ THE GRIND — LINKED LIST

Add Two Numbers

MEDIUM✓ CHIP-TIMEDLC #2 — FULL STATEMENT ↗

The drill: Add two non-negative integers that are each stored as a linked list with the least significant digit first, carrying between nodes exactly like grade-school addition — the sum comes back in that same reversed-digit format.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Two non-negative integers arrive stored as singly linked lists, with each node holding a single digit and the least significant digit sitting at the head of each list — the reverse of how the number would normally be written.

The job is to add the two numbers together and hand back the sum in that same format: a linked list of digits, least significant first, built from scratch rather than mutating either input.

The lists can be different lengths, and a carry can ripple all the way through — even producing one extra digit beyond the longer of the two input lists.

EX 01
l1 = [5, 6] · l2 = [4]
[9, 6]
65 + 4 = 69
EX 02
l1 = [0] · l2 = [0]
[0]
ZERO PLUS ZERO
EX 03
l1 = [7, 1, 6] · l2 = [5, 9, 2]
[2, 1, 9]
617 + 295 = 912
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Reconstructing each list as one big number, adding, and splitting the sum back into digits works — but only because the language's integers can hold a number of any size. What if they couldn't?

HINT 2 THE STRUCTURE

Grade-school addition never needs the whole number at once — only the current column and whatever carried over from the last one.

HINT 3 ONE STEP FROM THE ANSWER

Walk both lists together, summing corresponding digits plus a running carry; the new digit is that sum mod 10, and sum divided by 10 carries into the next column — keep going past the shorter list until both lists and the carry are exhausted.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE CARRY WALKPATTERN · DIGIT-BY-DIGIT CARRYl1 = [7,1,6] (617) · l2 = [5,9,2] (295)
7
1
6
5
9
2
STEP 1

Add 617+295 stored least-significant-digit-first: l1 reads 7,1,6 and l2 reads 5,9,2. Walk both together one column at a time, carrying between columns.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/add-two-numbers.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)
        tail = dummy
        carry = 0

        while l1 or l2 or carry:
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0
            total = v1 + v2 + carry
            carry, digit = divmod(total, 10)
            tail.next = ListNode(digit)
            tail = tail.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        return dummy.next
TIME O(MAX(N,M))SPACE O(MAX(N,M))PYTHON · RACE PACE · 17 LN

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