Add Two Numbers II (LeetCode 445): Solution and Explanation
The digits are stored most significant first, but addition has to start from the ones column. Pushing each list onto a stack flips the order without touching the input, and prepending every new digit node to the answer puts the result back in most significant first order.
Intuition
Column addition works right to left, while a singly linked list can only be walked left to right. A stack is the simplest way to read a sequence backwards: push everything, then pop.
Once digits come out ones first, the loop is the familiar one from Add Two Numbers: add two digits plus a carry, keep total % 10 and pass total // 10 along. The only twist is where the new node goes. Inserting it in front of the current head means the last digit created, the most significant one, ends up first, so no final reverse is needed.
Approach: Two stacks and head insertion
- Walk l1 and push each digit onto s1, then walk l2 and push each digit onto s2. The ones digit of each number is now on top.
- Set carry = 0 and head = null.
- While s1 or s2 is non-empty or carry is not 0, start total at carry and add the popped top of each non-empty stack.
- Set carry = total // 10, create a node holding total % 10, point it at head and make it the new head.
- Return head. A leftover carry naturally adds one more leading node, as in 999 + 1.
Step-by-step example
l1 = [7,2,4,3], l2 = [5,6,4]
- Push l1 to get s1 = [7,2,4,3] with 3 on top, and push l2 to get s2 = [5,6,4] with 4 on top.
- Ones column: 3 + 4 + 0 = 7, so create node 7 as the head. carry = 0.
- Tens column: 4 + 6 + 0 = 10, so create node 0 in front: 0 -> 7. carry = 1.
- Hundreds column: 2 + 5 + 1 = 8, giving 8 -> 0 -> 7. carry = 0.
- Thousands column: s2 is empty, so 7 + 0 + 0 = 7, giving 7 -> 8 -> 0 -> 7. Both stacks are empty and carry is 0, so return [7,8,0,7].
Code: Python, Java, C++
1class Solution:
2 def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
3 s1, s2 = [], []
4 while l1:
5 s1.append(l1.val)
6 l1 = l1.next
7 while l2:
8 s2.append(l2.val)
9 l2 = l2.next
10 carry = 0
11 head = None
12 while s1 or s2 or carry:
13 total = carry
14 if s1:
15 total += s1.pop()
16 if s2:
17 total += s2.pop()
18 carry = total // 10
19 node = ListNode(total % 10)
20 node.next = head
21 head = node
22 return head1class Solution {
2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
3 Deque<Integer> s1 = new ArrayDeque<>(), s2 = new ArrayDeque<>();
4 while (l1 != null) {
5 s1.push(l1.val);
6 l1 = l1.next;
7 }
8 while (l2 != null) {
9 s2.push(l2.val);
10 l2 = l2.next;
11 }
12 int carry = 0;
13 ListNode head = null;
14 while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
15 int total = carry;
16 if (!s1.isEmpty()) total += s1.pop();
17 if (!s2.isEmpty()) total += s2.pop();
18 carry = total / 10;
19 ListNode node = new ListNode(total % 10);
20 node.next = head;
21 head = node;
22 }
23 return head;
24 }
25}1class Solution {
2public:
3 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
4 stack<int> s1, s2;
5 while (l1) {
6 s1.push(l1->val);
7 l1 = l1->next;
8 }
9 while (l2) {
10 s2.push(l2->val);
11 l2 = l2->next;
12 }
13 int carry = 0;
14 ListNode* head = nullptr;
15 while (!s1.empty() || !s2.empty() || carry) {
16 int total = carry;
17 if (!s1.empty()) { total += s1.top(); s1.pop(); }
18 if (!s2.empty()) { total += s2.top(); s2.pop(); }
19 carry = total / 10;
20 ListNode* node = new ListNode(total % 10);
21 node->next = head;
22 head = node;
23 }
24 return head;
25 }
26};Time and space complexity
O(m + n)
Each node is pushed once and popped once, and the addition loop runs max(m, n) + 1 times at most.
O(m + n)
The two stacks hold every digit of both lists. The output list is not counted.
Other approaches
Reverse, add, reverse (time O(m + n), space O(1))
Reverse both lists in place, run the Add Two Numbers loop from the ones digit, then reverse the result. It uses constant extra space but modifies the inputs, which the follow up asks you to avoid.
Pad and recurse (time O(m + n), space O(m + n))
Compute both lengths, pad the shorter list with leading zeros conceptually, and recurse to the end so the carry is returned on the way back up. It avoids explicit stacks but uses the call stack, which is the same O(m + n) space and more code.
Convert to integers (time O(m + n), space O(m + n))
Turn each list into a number, add, and split the sum into digits. It breaks in fixed width languages because 100 digit numbers overflow 64 bit integers.
Common mistakes
- Stopping the loop when both stacks are empty but carry is still 1, which drops the leading digit of sums like 999 + 1.
- Appending new digits at the tail, which produces the answer in reverse order.
- Converting the lists to built in integers. Up to 100 digits do not fit in a long in Java, C++, C# or Go.
- Popping from an empty stack instead of treating its digit as 0 when the lists have different lengths.
Frequently asked questions
How is this different from Add Two Numbers?
In Add Two Numbers the lists store the ones digit first, so you can add while walking forward. Here the most significant digit comes first, so you need a way to visit digits backwards, and the result must also be built most significant first.
Can I solve it without modifying the input lists?
Yes. The stack approach only reads the input nodes. It never changes a next pointer in l1 or l2, which is what the follow up asks for.
Why insert at the head instead of at the tail?
Digits are produced from the ones column upwards. Inserting each new node in front of the previous head means the final head is the most significant digit, which is exactly the required order.
Can the answer have a leading zero?
No. The loop only runs an extra time when there is a carry, and that creates a leading 1. Neither input has leading zeros, so the top column is never 0 unless both numbers are 0.