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.
- 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.
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.
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.
Approach
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?
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Stopping before the last carry
while l1 or l2:
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
l1 = l1.next l2 = l2.next
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
long long x = 0, m = 1; for (ListNode* p = l1; p; p = p->next, m *= 10) x += p->val * m;
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.
Edge cases
[0]One step runs with total 0 and no carry, so the result is the single node [0], not an empty list.
Complexity
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.