Add Two Numbers
Difficulty: Medium · Pattern: Linked List · LeetCode #2
Two non-negative integers are stored as linked lists of digits in reverse order (the ones digit first). Return their sum as a linked list in the same format.
Examples
text
(2 → 4 → 3) + (5 → 6 → 4) = 7 → 0 → 8 (342 + 465 = 807)
(0) + (0) = 0
(9 → 9 → 9 → 9) + (9 → 9) = 8 → 9 → 0 → 0 → 1Hints
- Reverse order means you can add from the head, like grade-school addition.
- Continue while either list has digits or there's a carry.
Approach
Walk both lists simultaneously with a carry. At each step: s = (l1.val or 0) + (l2.val or 0) + carry, append the digit s % 10, and set carry = s // 10. Continue while any list remains or carry > 0. A dummy head simplifies building the result. O(max(m, n)).
Complexity
Time: O(max(m, n)). Space: O(max(m, n)) for the output.
Python solution
def addTwoNumbers(l1, l2):
dummy = tail = ListNode()
carry = 0
while l1 or l2 or carry:
s = carry + (l1.val if l1 else 0) + (l2.val if l2 else 0)
carry, digit = divmod(s, 10)
tail.next = ListNode(digit); tail = tail.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.nextJavaScript solution
function addTwoNumbers(l1, l2) {
const dummy = new ListNode(); let tail = dummy, carry = 0;
while (l1 || l2 || carry) {
const s = carry + (l1 ? l1.val : 0) + (l2 ? l2.val : 0);
carry = Math.floor(s / 10); tail.next = new ListNode(s % 10); tail = tail.next;
l1 = l1 && l1.next; l2 = l2 && l2.next;
}
return dummy.next;
}