Add Two Numbers

Medium

Topics
Linked ListMathRecursion

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, one digit per node. Add the two numbers and return the sum as a linked list, also in reverse order.

Example 1

l1243null
l2564null
sum708null
produced a carry
Digits are stored least significant first, which is exactly the order addition wants — so the lists are walked forwards with a running carry, no reversal needed. A carry left over at the end adds one more node.
Each list holds one number, least significant digit at the head.
Input:  l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2

l1999null
l21null
sum0001null
produced a carry
Input:  l1 = [9,9,9], l2 = [1]
Output: [0,0,0,1]

Constraints

  • 1 <= list length <= 100
  • 0 <= Node.val <= 9
  • No leading zeros except the number 0 itself.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Reverse-order storage is convenient: the heads are the least significant digits, so you can add left to right exactly like grade-school addition, carrying into the next node.

Approach

  1. Walk both lists together with a running carry.
  2. At each step sum the two current digits plus carry; the new node value is sum % 10, the new carry is sum // 10.
  3. Continue while either list has nodes or a carry remains.

Dry Run

l1 = 9 -> 9 -> 9      l2 = 1        --  digits are stored least significant first,
                                      so 999 + 1, and the carry flows forwards
  9 + 1 + carry 0 = 10   digit 0, carry 1    built 0
  9 + 0 + carry 1 = 10   digit 0, carry 1    built 0 0
  9 + 0 + carry 1 = 10   digit 0, carry 1    built 0 0 0
  both lists done, carry 1 = 1   digit 1, carry 0   built 0 0 0 1
answer 0 -> 0 -> 0 -> 1    (which reads as 1000)
The loop condition is `while l1 or l2 or carry`, and the third clause is the whole
point of this example. After three rounds both lists are exhausted but a carry is
still outstanding; drop `or carry` and the result is 0 0 0, silently losing the
leading 1.
Least-significant-first storage is what makes this easy. Addition propagates from
the low end, which is also the head of the list, so one forward pass needs no
reversal and no length comparison.
The dummy head removes the "is this the first node?" branch, and the two `if l1` /
`if l2` guards remove the "which list is longer?" branch. Between them the loop
body has no special cases at all.

Complexity

  • Time — O(max(m,n)): one pass over the longer list.
  • Space — O(max(m,n)): the output list.

Common Pitfalls

  • Do not forget the final carry — 999 + 1 grows the list by a node.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def addTwoNumbers(self, l1, l2):
        dummy=ListNode(); tail=dummy; carry=0
        while l1 or l2 or carry:
            s=carry
            if l1: s+=l1.val; l1=l1.next
            if l2: s+=l2.val; l2=l2.next
            carry,digit=divmod(s,10)
            tail.next=ListNode(digit); tail=tail.next
        return dummy.next
SensAI
Beta
Tap the mic to stop voice mode