Add Two Numbers (LeetCode 2): Solution and Explanation

Medium
Linked List
Math
Recursion

Two non-negative integers are stored as linked lists, one digit per node, with the least significant digit first. Add the numbers and return the sum as a linked list in the same reversed format.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The tempting shortcut is to convert each list into an integer, add them, and convert the sum back into a list. That works in Python thanks to arbitrary precision integers, but the lists can have up to 100 nodes, which overflows 64-bit integers in Java or C++. It also skips the point of the exercise, which is to work with the structure directly.

The useful observation is that the digits are already stored in the order you need. Grade-school addition starts from the ones place and moves left, carrying whenever a column sums to 10 or more. Since the head of each list is the ones digit, walking both lists from the head forward is exactly the column-by-column order of manual addition.

At each step you add the two current digits plus the carry from the previous column. The new digit is total % 10 and the new carry is total // 10, which is always 0 or 1. When one list is shorter, treat its missing digits as zero. When both lists end but a carry remains, for example 5 + 5, you still need one more node holding that 1.

A dummy head node keeps the construction clean. You always append to curr.next, so there is no special case for the very first digit, and at the end you return dummy.next. Folding the final carry into the loop condition, while l1 or l2 or carry, removes the need for a separate cleanup step.

Approach: Elementary addition with carry

  1. Create a dummy node and a pointer curr to it, and set carry = 0.
  2. Loop while l1, l2 or carry is still non-zero.
  3. Read val1 and val2 from the current nodes, using 0 for a list that has already ended.
  4. Compute total = val1 + val2 + carry, set carry = total // 10, and append a new node holding total % 10.
  5. Advance curr to the new node and move l1 and l2 forward if they are not already None.
  6. Return dummy.next, the head of the sum list.

Step-by-step example

l1 = [2,4,3], l2 = [5,6,4] (that is, 342 + 465)
  1. First column: 2 + 5 + 0 = 7. Append 7, carry stays 0.
  2. Second column: 4 + 6 + 0 = 10. Append 0, carry becomes 1.
  3. Third column: 3 + 4 + 1 = 8. Append 8, carry becomes 0.
  4. Both lists are exhausted and carry is 0, so the loop stops.
  5. The result is [7,0,8], which represents 807, and 342 + 465 is indeed 807.

Code: Python, Java, C++

1class Solution:
2    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
3        dummy = ListNode(0)
4        curr = dummy
5        carry = 0
6
7        while l1 or l2 or carry:
8            val1 = l1.val if l1 else 0
9            val2 = l2.val if l2 else 0
10
11            total = val1 + val2 + carry
12            carry = total // 10
13            curr.next = ListNode(total % 10)
14            curr = curr.next
15
16            l1 = l1.next if l1 else None
17            l2 = l2.next if l2 else None
18
19        return dummy.next

Time and space complexity

Time

O(max(m, n))

The loop runs once per digit of the longer list, plus at most one extra iteration for a final carry, and each iteration does constant work.

Space

O(max(m, n))

The output list has at most max(m, n) + 1 nodes. Apart from the output, only a few pointers and the carry are used, so auxiliary space is O(1).

Other approaches

Recursive addition (time O(max(m, n)), space O(max(m, n)))

Write a helper that takes two nodes and a carry, creates the current digit node, and sets its next to the recursive result for the following nodes. It reads elegantly but uses O(max(m, n)) call stack.

Convert to integers (time O(max(m, n)), space O(max(m, n)))

Build each number by walking its list, add them, and rebuild a list from the sum's digits. It only works in languages with big integers and is usually not what an interviewer wants to see.

Common mistakes

  • Dropping the final carry. Without or carry in the loop condition, 5 + 5 returns [0] instead of [0,1].
  • Stopping when the shorter list ends instead of continuing with zeros for the missing digits.
  • Advancing l1 or l2 with .next after it has already become None, which raises an attribute error on the uneven lists.
  • Reversing the input lists first. The digits are already least significant first, which is the order addition needs.

Frequently asked questions

Why are the digits stored in reverse order?

Storing the ones digit at the head means you can add from the least significant digit forward, which is how carries propagate. If the digits were in normal order you would need to reverse the lists or use a stack first.

What is the time complexity of Add Two Numbers?

It is O(max(m, n)), where m and n are the list lengths. Each digit is visited once, with possibly one extra step for a leftover carry.

Why use a dummy head node?

A dummy node gives you a fixed place to start appending, so the first digit is handled the same way as every other digit. You return dummy.next at the end.

Can the carry ever be more than 1?

No. The largest possible column sum is 9 + 9 + 1 = 19, so the carry is always 0 or 1.