Add Two Numbers

Pattern: Traversal and dummy nodes

medium

The digits are stored smallest first, which is exactly the order of school addition. Walk both lists together, add the digits and the carry, write one digit into a new list, and carry the rest.

The problem

Two non-negative whole numbers are stored in linked lists with their digits in reverse order, one digit per node, so the head holds the ones digit. Return their sum as a list in the same form. For example, 2 → 4 → 3 and 5 → 6 → 4 give 7 → 0 → 8, because 342 + 465 = 807.

The function name addTwoNumbers matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • In which order do you add digits by hand? How does that match the lists?
  • What happens when one list is longer?
  • When does the answer get one more digit than both inputs?

Hints

    Brute force, and why it fails

    Convert both lists to numbers, add, and convert back: overflows for long lists. Digit-by-digit addition works for any length, in O(max(m, n)).

    The key insight

    The reversed order is a gift: it is the order addition already uses, so the carry flows forward with the walk and never needs to go back.

    Dry run

    2 4 30 
    5 6 41 
    carry0
    out

    l1 = 2 → 4 → 3 (the number 342) and l2 = 5 → 6 → 4 (465). Start with carry 0.

    Step 1 of 4

    The plan

    dummy, tail = new node, carry = 0
    while l1 or l2 or carry:
        sum = carry + (l1.val if l1) + (l2.val if l2)
        advance l1 and l2 if they exist
        tail.next = new node(sum mod 10); tail = tail.next
        carry = sum / 10
    return dummy.next
    

    Complexity

    Time
    O(max(m, n))
    Space
    O(max(m, n))

    One step per digit of the longer number, plus one for a final carry. The answer list is the output.

    Edge cases

    • Different lengths, as in 9 9 9 9 9 9 9 and 9 9 9 9.
    • A final carry, as in 5 and 5: the answer is 0 → 1.
    • Both are 0: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(0), tail = dummy;
            int carry = 0;
            while (l1 != null || l2 != null || carry != 0) {     // digits come smallest first
                int sum = carry;
                if (l1 != null) { sum += l1.val; l1 = l1.next; }
                if (l2 != null) { sum += l2.val; l2 = l2.next; }
                tail.next = new ListNode(sum % 10);             // write one digit
                tail = tail.next;
                carry = sum / 10;                               // carry the rest
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode dummy(0);
            ListNode* tail = &dummy;
            int carry = 0;
            while (l1 != NULL || l2 != NULL || carry != 0) {    // digits come smallest first
                int sum = carry;
                if (l1 != NULL) { sum += l1->val; l1 = l1->next; }
                if (l2 != NULL) { sum += l2->val; l2 = l2->next; }
                tail->next = new ListNode(sum % 10);            // write one digit
                tail = tail->next;
                carry = sum / 10;                               // carry the rest
            }
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
            dummy = tail = ListNode(0)
            carry = 0
            while l1 is not None or l2 is not None or carry:   # digits come smallest first
                total = carry
                if l1 is not None:
                    total += l1.val
                    l1 = l1.next
                if l2 is not None:
                    total += l2.val
                    l2 = l2.next
                tail.next = ListNode(total % 10)    # write one digit
                tail = tail.next
                carry = total // 10                 # carry the rest
            return dummy.next

    Common mistakes

    • Stopping when both lists end, which drops a final carry.
    • Converting to an integer type, which overflows for long numbers.
    • Advancing a list that has already ended.

    Similar problems