Algorithm

Add Two Numbers

Linked List Pattern

Add Two Numbers

You are given two non-negative integers, each stored as a singly linked list of single digits with the ones digit at the head — the digits are in reverse order, so 342 is stored as 2 → 4 → 3. Return their sum in the same form: a new linked list of digits, ones-first. The two lists may have different lengths, and the result may be longer than both (a final carry adds one more digit). Neither input has leading zeros, except the number 0 itself, which is the single node [0].

CONSTRAINTS
  • The number of nodes in each list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • No leading zeros except the number 0 itself.
EXAMPLE 1
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Reversed, the inputs are 342 and 465; their sum is 807, which stored ones-first is 7 → 0 → 8. The middle digit is 0 because 4 + 6 = 10 spills a carry into the next column.
EXAMPLE 2
Input: l1 = [0], l2 = [0]
Output: [0]
Both numbers are 0, so the sum is 0 — a single-digit result, [0].
EXAMPLE 3
Input: l1 = [9,9,9,9], l2 = [9,9,9]
Output: [8,9,9,0,1]
This is 9999 + 999 = 10998. The result has five digits — one more than the longer input — because the top column overflows and a final carry becomes its own leading digit.
Why are the digits stored in reverse order — is that a complication?
It's the opposite: reverse order puts the ones digit at the head, so walking forward from the heads processes columns least-significant first, which is the exact direction carries flow in hand addition. It removes work rather than adding it.
What if the two lists have different lengths?
Treat the shorter list's missing high-order digits as 0. A number like 45 is just 045 when you need a hundreds digit, so padding with zero keeps the column addition correct.
What happens if a carry remains after both lists are exhausted?
You must append one more node for it — that final carry is always 1 and it makes the result one digit longer than either input. This is exactly the case people forget, so the loop has to keep running while a carry is pending.
Can I just convert each list to an integer, add, and convert back?
Risky. Each number can be 100 digits, which overflows fixed-width integer types in most languages. Adding digit by digit in the given representation avoids the overflow entirely, so it's the robust approach.

We are given two numbers, but not as integers — each is a chain of single digits, one digit per node, stored reversed so the ones place comes first. We must add them and return the sum in the same reversed-digit form. The reversal looks like an obstacle; it is actually a gift, and seeing why is the whole insight.

The tempting shortcut, and why it's fragile

The obvious plan: walk each list to rebuild its integer, add the two integers, then break the sum back into digit nodes. It reads cleanly and, in a language with unbounded integers like Python, it even works. But it quietly leans on something the problem is engineered to break. Each list can hold up to 100 digits — a 100-digit number. In most languages (C++, Java, Go) a machine integer tops out around 19 digits; feeding it a 100-digit value overflows and silently produces garbage. The shortcut converts the numbers to a form that cannot hold them. The digit-by-digit structure we were given is precisely the representation that has no size limit — so the robust solution should add in that representation directly, never assembling the whole number at all.

The reframe: reversed digits are exactly paper addition

Think about how you add by hand. You line the numbers up on the right and start at the ones column, because a carry only ever flows from a smaller place to a larger one — right to left. That direction is the catch when digits are stored most-significant-first, because you'd have to reach the ends of both lists before you could even begin. But here the lists are reversed: the head of each list is the ones digit. Walking both lists forward from their heads therefore visits the columns in exactly the order hand-addition needs — ones, then tens, then hundreds. The reversal has pre-aligned the numbers for us. A single simultaneous forward traversal of both lists is long addition.

The mechanism: one column at a time, carry threaded through

Walk both lists together. At each step take a digit from each (0 if that list has run out — a shorter number is just padded with leading zeros in the higher places), add them plus the carry left over from the previous column. That total is between 0 and 18 + a carry, so the digit we write is total % 10 and the carry we pass to the next column is total // 10 (either 0 or 1). We build the result with a dummy node: a throwaway node sitting before the real head so that appending the first digit is the same code as appending every other digit — no special case for an empty result. At the end we return dummy.next, the real head.

python
dummy = Node(0)      # placeholder so the first append is not a special case
curr = dummy
carry = 0

while l1 or l2 or carry:          # keep going while ANY of the three has work
    v1 = l1.val if l1 else 0      # a missing digit counts as 0
    v2 = l2.val if l2 else 0
    total = v1 + v2 + carry
    carry = total // 10           # 0 or 1, flows to the next column
    curr.next = Node(total % 10)  # the digit stored in this column
    curr = curr.next
    l1 = l1.next if l1 else None
    l2 = l2.next if l2 else None

return dummy.next
Crucial Notethe loop continues while l1 or l2 or carry — and that final or carry is the piece everyone forgets. When both lists end but the last column produced a carry, there is still one more digit to write, and it lengthens the result beyond either input. Adding 9999 + 999, the highest column gives 9 + 0 + 1 = 10: after both lists are exhausted a carry of 1 remains, and it must become its own new leading node, turning a 4-digit and 3-digit input into a 5-digit answer. Dropping the or carry test silently loses that top digit. The if l1 else 0 on each side is the same idea one level down: it lets lists of different lengths add correctly by treating the shorter one's missing high digits as zero, instead of crashing when one list ends first.
Worked Example:[9,9,9,9] + [9,9,9] (that is 9999 + 999)
- Column 0: 9 + 9 + carry 0 = 18. Write 8, carry 1. Result so far: 8.
- Column 1: 9 + 9 + carry 1 = 19. Write 9, carry 1. Result: 8 → 9.
- Column 2: 9 + 9 + carry 1 = 19. Write 9, carry 1. Result: 8 → 9 → 9.
- Column 3: 9 + (nothing, treat as 0) + carry 1 = 10. Write 0, carry 1. Result: 8 → 9 → 9 → 0.
- Both lists are now empty, but carry is 1 — the loop runs once more: 0 + 0 + 1 = 1. Write 1, carry 0. Result: 8 → 9 → 9 → 0 → 1.
- carry is 0 and both lists are done: stop. The list [8,9,9,0,1] reads, reversed, as 10998 — and 9999 + 999 = 10998. The answer is one digit longer than either input, exactly as the trailing carry demanded.
The reflex this builds

The cost is O(max(N, M)) time — one pass over the longer list — and O(max(N, M)) space for the result we must produce. Two habits generalize past this problem. First, simulate the pencil-and-paper method directly when a problem hands you a number in an unusual representation; don't rush to convert to a native integer that may not fit — the given representation is often chosen because it has no size ceiling. Second, meet the dummy-node builder: whenever you construct a linked list from nothing, a throwaway head node erases the "is this the first element?" special case, and you'll reuse it unchanged in Merge Two Sorted Lists and anywhere a list is assembled node by node. The one piece of genuine state here — the carry — is a value threaded from each step to the next; spotting "what single fact must survive between iterations" is the same skill that runs through the fast/slow and reversal problems ahead.

Interactive Strategy Visualization

Digit-by-Digit Addition

Strategy: Two-Pointer Simulation
Memory: O(1) excluding output
List 1 (v1)
2
4
List 2 (v2)
5
6
Result
Operation
2 + 5 + 0 = 7
Carry Out
0
Digit for List
-
1. Summing the Ones
Add head nodes from both lists. Sum is 7, no carry needed.
O(max(N, M)) Time · O(max(N, M)) Space Column Addition with Carry