Add Two Numbers (LeetCode 2): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create a
dummynode and a pointercurrto it, and setcarry = 0. - Loop while
l1,l2orcarryis still non-zero. - Read
val1andval2from the current nodes, using 0 for a list that has already ended. - Compute
total = val1 + val2 + carry, setcarry = total // 10, and append a new node holdingtotal % 10. - Advance
currto the new node and movel1andl2forward if they are not already None. - 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)
- First column: 2 + 5 + 0 = 7. Append 7, carry stays 0.
- Second column: 4 + 6 + 0 = 10. Append 0, carry becomes 1.
- Third column: 3 + 4 + 1 = 8. Append 8, carry becomes 0.
- Both lists are exhausted and carry is 0, so the loop stops.
- 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.next1class Solution {
2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
3 ListNode dummy = new ListNode(0);
4 ListNode curr = dummy;
5 int carry = 0;
6
7 while (l1 != null || l2 != null || carry != 0) {
8 int val1 = (l1 != null) ? l1.val : 0;
9 int val2 = (l2 != null) ? l2.val : 0;
10
11 int total = val1 + val2 + carry;
12 carry = total / 10;
13 curr.next = new ListNode(total % 10);
14 curr = curr.next;
15
16 l1 = (l1 != null) ? l1.next : null;
17 l2 = (l2 != null) ? l2.next : null;
18 }
19
20 return dummy.next;
21 }
22}1class Solution {
2public:
3 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
4 ListNode dummy(0);
5 ListNode* curr = &dummy;
6 int carry = 0;
7
8 while (l1 || l2 || carry) {
9 int val1 = l1 ? l1->val : 0;
10 int val2 = l2 ? l2->val : 0;
11
12 int total = val1 + val2 + carry;
13 carry = total / 10;
14 curr->next = new ListNode(total % 10);
15 curr = curr->next;
16
17 l1 = l1 ? l1->next : nullptr;
18 l2 = l2 ? l2->next : nullptr;
19 }
20
21 return dummy.next;
22 }
23};Time and space complexity
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.
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 carryin 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
l1orl2with.nextafter 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.