LeetCode #2 Medium

Add Two Numbers

Add Two Numbers is LeetCode 2 (Medium). Two non-empty linked lists each store a non-negative number, one digit per node, in reverse order: the head holds the ones digit. Return the sum as a linked list in the same reverse order.

  • The lists can have different lengths, from 1 to 100 nodes each.
  • Neither number has leading zeros, except the number 0 itself.

A 100-digit number does not fit in any built-in integer type of C++ or Java, so the digits are added one node at a time.

Constraints
  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.
linked-listmathrecursion
Open on LeetCode ↗
02

Intuition

Reverse order is what makes this easy. Addition on paper starts at the ones digit, and the ones digit is the head of each list, so walking both lists forward is column addition from right to left.

At each step add the two digits and the carry:

  • New node: total % 10.
  • Carry: total // 10. The largest total is 9 + 9 + 1 = 19, so the carry is always 0 or 1.

The walk continues while either list has nodes or a carry is left, so a final carry turns into one more node.

How to spot this pattern

Numbers stored digit by digit in a list or string, too long for an integer, mean simulating addition column by column. Add Binary (LeetCode 67) and Add Strings (LeetCode 415) use the same loop on strings.

03

Approach

Try it first

Before reading on, decide which digit of each number the head node holds, and why that order helps. Then decide when your loop may stop: what if one list is longer, and what if a carry is left at the end?

1

Start behind a dummy node

Create dummy = ListNode(0) and a pointer tail to it, and set carry = 0. Every new digit is attached at tail.next, so the first digit needs no special case, and dummy.next is the answer at the end.

2

Read one digit from each list

Take a = l1.val if l1 exists, else 0, and the same for b from l2. A finished list acts like a number padded with zeros on the left, which does not change the sum.

3

Write the digit and keep the carry

Compute carry, digit = divmod(a + b + carry, 10). Append ListNode(digit) at tail and move tail to it. Then move l1 and l2 to their next nodes, but only the ones that are not already None.

4

Loop until both lists and the carry are used up

Run while l1 or l2 or carry. The carry part adds the extra node when the sum has more digits than either input, as in 999 + 1 = 1000.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def addTwoNumbers(self, l1, l2):
▶3 dummy = tail = ListNode(0)
▶4 carry = 0
▶5 while l1 or l2 or carry:
▶6 a = l1.val if l1 else 0
▶7 b = l2.val if l2 else 0
▶8 carry, digit = divmod(a + b + carry, 10)
▶9 tail.next = ListNode(digit)
▶10 tail = tail.next
▶11 l1 = l1.next if l1 else None
▶12 l2 = l2.next if l2 else None
▶13 return dummy.next
l1l2sum243null564null0dummytailno digits added yetheads hold the ones digits → start there
l1342as a number
l2465as a number
carry0
Read right to left, the lists are the numbers 342 and 465. Their heads are the ones digits, so walking forward adds the columns in the order you would on paper. The dummy node gives the first new digit something to hang from.
l1l2sum243null564null0dummytail2+5+0=7→70l1l2carry intotalnew nodecarry out2 + 5 + carry 0 = 7
a2
b5
total7
Both lists still have a digit here. The column total is 7.
l1l2sum243null564null0dummy7tail2+5+0=7→70l1l2carry intotalnew nodecarry outnew node 7, no carry
digit7
carry0
The new node holds 7, the last digit of 7, and tail moves onto it. Nothing is carried. Both list pointers that still had a node move one step on.
l1l2sum243null564null0dummy7tail4+6+0=10→01l1l2carry intotalnew nodecarry out4 + 6 + carry 0 = 10
a4
b6
total10
Both lists still have a digit here. The column total is 10.
l1l2sum243null564null0dummy70tail4+6+0=10→01l1l2carry intotalnew nodecarry outnew node 0, carry 1 to the next digit
digit0
carry1
The new node holds 0, the last digit of 10, and tail moves onto it. The 10 that does not fit becomes a carry of 1 for the next digit; it can never be more than 1, since 9 + 9 + 1 = 19. Both list pointers that still had a node move one step on.
l1l2sum243null564null0dummy70tail3+4+1=8→80l1l2carry intotalnew nodecarry out3 + 4 + carry 1 = 8
a3
b4
total8
Both lists still have a digit here. The column total is 8.
l1l2sum243null564null0dummy708tail3+4+1=8→80l1l2carry intotalnew nodecarry outnew node 8, no carry
digit8
carry0
The new node holds 8, the last digit of 8, and tail moves onto it. Nothing is carried. Both list pointers that still had a node move one step on.
l1l2sum243null564null0dummy708nothing left to addanswer: 7 → 0 → 8, which is 807
result[7, 0, 8]342 + 465 = 807
Both lists and the carry are used up. The answer starts at dummy.next, skipping the placeholder: [7, 0, 8], which read right to left is 342 + 465 = 807.
05

Common pitfalls

Stopping before the last carry

✗ Wrong
while l1 or l2:
✓ Right
while l1 or l2 or carry:

When the top digits overflow, the sum needs one node more than the longer list. For [5] and [5] the short loop returns [0]; the answer is [0, 1].

Moving a pointer that is already None

✗ Wrong
l1 = l1.next
l2 = l2.next
✓ Right
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None

When the lists differ in length, one runs out first. For [9, 9] and [1], the second step reads None.next and raises AttributeError.

Converting the lists to integers

✗ Wrong
long long x = 0, m = 1;
for (ListNode* p = l1; p; p = p->next, m *= 10) x += p->val * m;
✓ Right
carry = total / 10;
tail->next = new ListNode(total % 10);

A long long holds about 19 digits and the lists hold up to 100. For a list of twenty 9s, x silently overflows and the returned list is wrong, with no error raised.

06

Edge cases

Both lists are [0]

One step runs with total 0 and no carry, so the result is the single node [0], not an empty list.

07

Complexity

Time
O(max(m, n))
Space
O(max(m, n))
m and n are the list lengths. The loop runs once per digit of the longer list, plus once for a final carry. The new list is the only storage, and it is the output; the extra space beyond it is O(1).
08

Add Two Numbers FAQ

What if the digits are stored with the most significant digit first?

That is Add Two Numbers II (LeetCode 445). The ones digits are now at the tails, so either reverse both lists, add them with this loop and reverse the result, or push each list's digits onto a stack and pop them, putting each new node at the front of the answer.

Can this be solved with recursion?

Yes. A function that takes two nodes and a carry builds one node from them and sets its next to the call for the two next nodes and the new carry, stopping when both nodes are None and the carry is 0. It runs in the same O(max(m, n)) time but uses up to 101 stack frames, where the loop uses none.