Add Two Numbers

Medium
2001.

Add Two Numbers

Add Two Numbers is a medium coding problem on math and recursion, asked in Amazon, Google, Microsoft and Bloomberg interviews.

Two non-negative integers are stored in two non-empty singly linked lists, l1 and l2, one decimal digit per node, with the digits in reverse order — the head holds the ones digit. Neither number has leading zeros, except the number 0 itself.

Return their sum as a linked list in the same reversed-digit form.

Example 1

Input
l1 = [2,4,3], l2 = [5,6,4]
Output
[7,0,8]
Explanation
342 + 465 = 807, stored as 7 → 0 → 8.

Example 2

Input
l1 = [0], l2 = [0]
Output
[0]

Example 3

Input
l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output
[8,9,9,9,0,0,0,1]
Explanation
9999999 + 9999 = 10009998; the final carry adds a new node.

Constraints

  • The number of nodes in each list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • Neither number has leading zeros, except the number 0 itself
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * Definition for singly-linked list (provided by the judge — do not redefine it):
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Add Two Numbers — Solution in Python, Java & C++

Add Two Numbers solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem on math and recursion.

Add Two Numbers is a medium coding problem on math and recursion, asked in Amazon, Google, Microsoft and Bloomberg interviews.

  • Difficulty: Medium
  • Topics: Math, Recursion
  • Asked at: Amazon, Google, Microsoft, Bloomberg
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Two non-negative integers are stored in two non-empty singly linked lists, l1 and l2, one decimal digit per node, with the digits in reverse order — the head holds the ones digit. Neither number has leading zeros, except the number 0 itself.

Return their sum as a linked list in the same reversed-digit form.

Example 1

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807, stored as 7 → 0 → 8.

Example 2

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Explanation: 9999999 + 9999 = 10009998; the final carry adds a new node.

Constraints

  • The number of nodes in each list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • Neither number has leading zeros, except the number 0 itself

Hints for Add Two Numbers

  1. Hint 1

    The heads are the ones digits, so the lists are already in the order grade-school addition works in.

  2. Hint 2

    Walk both lists together, adding the two digits and the carry; the new digit is sum % 10 and the new carry sum / 10.

  3. Hint 3

    Keep going while either list has nodes or the carry is non-zero — the last carry can create one extra node.

How to solve Add Two Numbers

Reversed digits mean the least significant digits come first, which is exactly the order column addition proceeds in. One simultaneous walk of both lists, with a carry, produces the answer digit by digit.

Approach

  1. Create a dummy node and a tail pointer; set carry = 0.
  2. While l1, l2 or carry is non-zero: sum = carry + (l1 ? l1.val : 0) + (l2 ? l2.val : 0).
  3. Append a node with sum % 10, set carry = sum / 10, and advance whichever lists are not exhausted.
  4. Return dummy.next.

Why it works

This is the column method: each output digit is the sum of the two digits in that column plus the carry from the column to its right, and the carry is always 0 or 1. Treating a finished list as contributing 0s handles numbers of different lengths.

Complexity

  • Time — O(max(m, n))
  • Space — O(max(m, n)) for the result list

Pitfalls

  • Converting the lists to built-in integers overflows — a number can have 100 digits.
  • Forgetting the final carry loses the leading 1 (e.g. 5 + 5 = 10).
  • The lists can have different lengths; keep reading the longer one after the shorter one ends.

Reference solution

Python

from typing import Optional

def addTwoNumbers(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
    dummy = ListNode(0)
    tail = dummy
    carry = 0
    while l1 or l2 or carry:
        total = carry
        if l1:
            total += l1.val
            l1 = l1.next
        if l2:
            total += l2.val
            l2 = l2.next
        tail.next = ListNode(total % 10)
        tail = tail.next
        carry = total // 10
    return dummy.next

Java

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0), tail = dummy;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        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);
        tail = tail.next;
        carry = sum / 10;
    }
    return dummy.next;
}

C++

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode dummy(0);
    ListNode* tail = &dummy;
    int carry = 0;
    while (l1 || l2 || carry) {
        int sum = carry;
        if (l1) { sum += l1->val; l1 = l1->next; }
        if (l2) { sum += l2->val; l2 = l2->next; }
        tail->next = new ListNode(sum % 10);
        tail = tail->next;
        carry = sum / 10;
    }
    return dummy.next;
}

JavaScript

var addTwoNumbers = function(l1, l2) {
    var dummy = new ListNode(0), tail = dummy, carry = 0;
    while (l1 !== null || l2 !== null || carry !== 0) {
        var 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);
        tail = tail.next;
        carry = Math.floor(sum / 10);
    }
    return dummy.next;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 337 math problems · the whole catalogue

Learn the technique: Recursion