15% off all plans & roadmaps Use code

See plans

Add Two Numbers

Updated

TL;DR: Two linked lists hold the digits of two numbers, least significant digit first. Walk both lists together, add digit by digit with a carry, and build the answer list as you go.

Problem

You are given two non-empty linked lists. Each one represents a non-negative integer. The digits are stored in reverse order, and every node holds a single digit. Add the two numbers and return the sum as a linked list in the same format.

You may assume neither number has leading zeros, except the number 0 itself.

Example 1

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

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]

Constraints

  • The number of nodes in each list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • Each list represents a number with no leading zeros.

Constraints that matter

  • Each list has up to 100 nodes, so a number can have 100 digits. That overflows a 64-bit integer, so converting to a built-in integer type fails in Java, C++, Go and C#.
  • Both lists have at least one node, so you never need to handle an empty input. The lists can still differ in length, so one pointer runs out before the other.
  • Digits are 0 to 9 and there are two inputs, so a column sum plus carry is at most 9 + 9 + 1 = 19. The carry is always 0 or 1.
  • The result can be one digit longer than the longer input (999 + 1 = 1000). The loop must keep running while a carry remains.
  • With at most 100 nodes per list, any linear pass is far below any time limit. The real challenge is correct pointer and carry handling, not speed.

View on LeetCode

Hints

Hint 1

This is column addition, the method you learned in school.

Hint 2

Read each list into a number, add the two numbers with normal arithmetic, then write the sum back out as a list.

Solution

Intuition

This is column addition, the method you learned in school. You line the numbers up at the ones digit, add each column, write the last digit of the column sum, and carry the rest to the next column.

It is like adding two long numbers on paper, one column at a time from the right. Each list node is one digit written in a column, the two pointers move down their columns together, and the carry variable is the small note you write above the next column.

The reverse storage is the hint. The head of each list is already the ones digit, so both pointers start aligned. You never need to reverse a list or find its end. You walk forward and the column order takes care of itself.

The only state that crosses from one column to the next is the carry. Since a column sum is at most 19, the carry is 0 or 1. That is why a single integer is enough memory for the whole problem.

Two details make or break the solution. When one list is shorter, treat its missing digits as 0. When both lists end and a carry of 1 is left, emit one more node. A loop condition that checks both pointers and the carry covers both cases at once.

Watch the pattern animation

Worked example

Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [7, 0, 8]
Explanation: The lists read as 342 and 465 because the head is the ones digit. Their sum is 807, which is stored backwards as 7 -> 0 -> 8.

Approach 1: Convert to integers, add, convert back

Read each list into a number, add the two numbers with normal arithmetic, then write the sum back out as a list. Most people try this first, because the problem reads like plain addition.

It needs big-integer support. Python has it built in. Java has BigInteger, JavaScript has BigInt, Go has math/big, and C# has System.Numerics.BigInteger. C++ has nothing in the standard library, so the C++ version stores each number as a digit string and adds the strings. That string addition is the carry loop in disguise, which is why the next approach is the real answer.

Steps

  1. Walk l1 and collect its digits in order. Reverse them to read the number from the most significant digit.
  2. Do the same for l2.
  3. Add the two big integers.
  4. Convert the sum to a decimal string, such as 807.
  5. Walk the string from its last character to its first.
  6. Append one new list node per character and return the head.

Dry run

On l1 = [2,4,3] and l2 = [5,6,4]:

  • Collect l1 digits 2, 4, 3. Reversed, they read 342.
  • Collect l2 digits 5, 6, 4. Reversed, they read 465.
  • The sum is 342 + 465 = 807, and its string is 807.
  • Read the string from the end: 7, then 0, then 8.
  • The built list is 7 -> 0 -> 8, which matches the expected output.

Complexity

TimeO(n + m)
SpaceO(n + m)

Let n and m be the lengths of the two lists. Reading each list touches every node once, big-integer addition costs time linear in the digit count, and writing the result touches at most max(n, m) + 1 digits. The digit strings and the big integers each hold O(n + m) digits, so the extra memory is linear as well. It also hides the idea the interviewer wants to see, and it relies on library big integers that you cannot assume in every language.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        def read(node):
            digits = []
            while node:
                digits.append(str(node.val))
                node = node.next
            # list order is least significant first, so reverse it
            return int(''.join(reversed(digits))), len(digits)

        a, n = read(l1)
        b, m = read(l2)
        total = a + b
        # pad with zeros so leading zeros of the number (trailing nodes) are kept
        s = str(total).zfill(max(n, m))
        dummy = ListNode(0)
        tail = dummy
        for ch in reversed(s):
            tail.next = ListNode(int(ch))
            tail = tail.next
        return dummy.next
Addition of Numbers pattern infographic for Add Two Numbers

Solution pattern

Addition of Numbers

Part of Linked List Manipulation Patterns

Approach 2: One pass with a carryOptimalAddition of Numbers

What's slow: the first approach makes three passes and builds two digit strings and a big integer before it produces a single output node. It also depends on a big-integer library, which C++ lacks. Both lists are already aligned at the ones digit, so none of that conversion is needed.

The insight that fixes it: add column by column while you walk. Keep one integer, carry, and one tail pointer into the result list. Each step adds the two current digits and the carry, writes total % 10 as a new node, and keeps total / 10 as the next carry.

Start with a dummy head node so the first real node attaches the same way as every later one. Loop while l1 exists, l2 exists, or carry is non-zero. A finished list contributes 0. Return dummy.next.

Steps

  1. Create a dummy node, set tail to it, and set carry to 0.
  2. Loop while l1 is not null, or l2 is not null, or carry is not 0.
  3. Start total at carry. Add l1.val and move l1 forward if l1 exists.
  4. Add l2.val and move l2 forward if l2 exists.
  5. Set carry to total / 10 and append a node with value total % 10 at tail.
  6. Move tail to the new node.
  7. When the loop ends, return dummy.next.

Dry run

On l1 = [2,4,3] and l2 = [5,6,4]. The table shows the state after each loop iteration.

Stepl1 digitl2 digitcarry intotalnew nodecarry outresult so far
12507707
246010017 -> 0
33418807 -> 0 -> 8

After step 3, both lists are null and the carry is 0, so the loop stops. The function returns dummy.next, which is 7 -> 0 -> 8.

Complexity

TimeO(max(n, m))
SpaceO(1)

Let n and m be the lengths of the two lists. Each iteration advances at least one input pointer or consumes the final carry. That gives at most max(n, m) iterations plus one for a leftover carry, and each iteration does constant work. So time is O(max(n, m)).

Auxiliary space is O(1): carry, total and two pointers. The output list has up to max(n, m) + 1 nodes, which the problem requires, so counting it makes total space O(max(n, m)).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)
        tail = dummy
        carry = 0
        # keep going while any input remains or a carry is left over
        while l1 or l2 or carry:
            total = carry
            if l1:
                total += l1.val
                l1 = l1.next
            if l2:
                total += l2.val
                l2 = l2.next
            carry, digit = divmod(total, 10)
            tail.next = ListNode(digit)
            tail = tail.next
        return dummy.next

Common mistakes

  • Writing while (l1 != null || l2 != null) and dropping || carry != 0. Then 5 + 5 returns [0] instead of [0, 1]. Keep the carry in the loop condition, or append a node after the loop when carry is 1.
  • Reading l1.val without a null check. The lists can have different lengths, so the shorter one hits null first. Guard each read with if l1 and treat a missing digit as 0.
  • Forgetting l1 = l1.next or l2 = l2.next. The loop condition never changes and the program runs until the judge kills it. Advance each pointer in the same branch where you read its value.
  • Using while (l1 && l2). This stops when the shorter list ends and drops the rest of the longer one, so 99 + 1 loses its tail. Use OR, with a 0 for the finished list.
  • Converting each list to int or long. A 100-digit number overflows a 64-bit integer and gives wrong answers on long inputs like Example 3. Add digit by digit with a carry instead.
  • Building the answer without a dummy head and special-casing the first node. That adds a branch inside the loop and often returns the wrong head. Use dummy and return dummy.next.

Edge cases

  • l1 = [0], l2 = [0]: the answer is [0]. One iteration gives total 0, and the carry stays 0, so there is no extra node.
  • l1 = [5], l2 = [5]: the answer is [0, 1]. The first column gives 10, and the final carry creates a new most significant node.
  • l1 = [9,9,9], l2 = [1]: the answer is [0, 0, 0, 1]. The carry ripples through every column and the last one makes a new node.
  • Lists of different lengths, such as [1,8] and [0]: the answer is [1, 8]. The finished list contributes 0 for the second column.
  • Example 3, 9,999,999 + 9,999: the answer is [8,9,9,9,0,0,0,1]. A carry runs through the short list and then keeps going through the longer one.
  • Both lists with 100 nines: the answer has 101 nodes, ending in a 1. This confirms no overflow and a correct final carry.

Follow-ups interviewers ask

What if the digits are stored in forward order, as in Add Two Numbers II?
The heads are now the most significant digits, so the alignment is wrong. Push each list onto a stack, then pop both stacks together to get the ones digits first. Add with a carry as before, and prepend each new node to the result so the final list reads in forward order. You can also reverse both lists, run this solution, and reverse the answer.
Can you do it without allocating a new list?
Yes. Write each digit into the longer list's existing nodes and reuse that list as the answer. When the shorter list ends, keep walking the longer one while a carry remains. If you run off the end with a carry of 1, append one new node. This mutates the input, so confirm that is allowed first.
How would you add k lists, or one number across many lists?
Walk all k lists together and sum k digits plus the carry in each column. The carry can then be larger than 1, up to about k - 1, but the same total / 10 and total % 10 logic works. Time is O(k * L) for L the longest length, and no big-integer type is needed.

Add Two Numbers FAQ

How do I add two numbers in LeetCode 2?

Walk both linked lists from the head, since the head is the ones digit. At each step add the two digits and the carry, store total % 10 in a new node, and keep total / 10 as the next carry. Stop only when both lists are exhausted and the carry is 0.

What is the time complexity of Add Two Numbers?

It is O(max(n, m)), where n and m are the list lengths. Each loop iteration consumes at least one input node or the final carry and does constant work. The result has at most max(n, m) + 1 nodes, so the number of iterations is bounded by that.

Why use a carry variable for Add Two Numbers?

A column sum is at most 9 + 9 + 1 = 19, so the only information that moves to the next column is a carry of 0 or 1. One integer holds all of it. That is what lets you finish in one pass without ever forming the full number, which could have 100 digits.

Can Add Two Numbers be solved in O(1) extra space?

Yes, if you do not count the output list. The one-pass solution keeps only carry, total and a few pointers. The output has up to max(n, m) + 1 nodes, so the total is O(max(n, m)) when you include it. You can lower even that by overwriting the longer input list, at the cost of mutating it.

How do I solve Add Two Numbers in Java or C++?

Use the same one-pass loop in both. In Java, create new ListNode(total % 10) and advance tail. In C++, do the same with new ListNode(...). Avoid converting to long or long long, because 100 digits overflow both.

Is Add Two Numbers the same as 2 Sum?

No. Two Sum asks for two array indices whose values add to a target and is solved with a hash map. Add Two Numbers is about adding two big numbers stored as linked lists and is solved with a carry loop. The two share only the number 2 in their titles and the word add.

Asked at

See which companies ask this — Pro

Practise it