Add Two Numbers

medium

You are given two non-empty linked lists that represent two non-negative integers. Each node holds a single digit, and the digits are stored in reverse order — the ones digit comes first, then the tens, then the hundreds, and so on.

Add the two numbers and return their sum as a linked list, in the same reverse-order format.

You may assume neither number has a leading zero, except the number 0 itself (a single node holding 0).

Hints

How did you add two multi-digit numbers by hand in school — and which column did you start from?
The head of each list is the ones digit, so walking the lists forward already lines up matching place values. What one small piece of information do you need to carry from each column to the next?
Sweep both lists together with a single carry. At each step append (sum % 10) and keep (sum / 10) — and remember a leftover carry may need its own final node.

Common doubts

Treat the missing digits as 0. Keep looping while either list still has nodes, substituting 0 for whichever list has run out.
Yes. A sum like [9] + [1] produces 10, so once both lists finish you may still have a carry of 1 that needs its own final node.
It gives you a fixed handle to attach the first real node to, so you avoid a special case for the head and simply return dummy.next at the end.

Interview follow-ups

Reverse both lists, add as usual, then reverse the result — or push each list's digits onto a stack and pop them together so you still process least-significant first.
The same column-by-column addition with a carry, walking both strings from the last character toward the first.

Fun facts

  • Because the digits arrive pre-reversed, this is actually easier than adding two numbers on paper — you never have to align lengths or scan to the end first.
  • The exact carry-propagation loop here is how a CPU's ripple-carry adder works in hardware, one bit-column at a time.

Asked at

AmazonMicrosoftGoogleBloombergAdobe
Frequently Sometimes Occasionally
Example 1
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
342 + 465 = 807, whose digits in reverse order are 7 -> 0 -> 8.
Example 2
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
9999999 + 9999 = 10009998.
Constraints

- The number of nodes in each list is in the range [1, 100]. - 0 <= Node.val <= 9 - Each list represents a number with no leading zeros (except the number 0 itself).

Solve this problem →