Skip to content
Problem 2 · LeetCode 2(opens in a new tab)

Add Two Numbers

MediumLinked lists

Two non-negative whole numbers are stored as linked lists, l1 and l2. Every node holds one digit, and the lowest digit comes first: the list 4 → 1 → 3 stands for 314.

Build and return a new linked list that holds their sum, written the same way, lowest digit first. Neither input has extra zeros at the front; a list can start and end with 0 only when it is the number 0.

Example 1

Input:  l1 = [5, 8, 2], l2 = [7, 3, 4]
Output: [2, 2, 7]
Why:    285 + 437 = 722
2 more examples and the constraints

Example 2

Input:  l1 = [9, 9], l2 = [1]
Output: [0, 0, 1]
Why:    99 + 1 = 100; the final carry adds a node

Example 3

Input:  l1 = [0], l2 = [4, 1]
Output: [4, 1]
Why:    0 + 14 = 14

Constraints

  • 1 ≤ nodes in each list ≤ 100
  • 0 ≤ each digit ≤ 9
  • The last node (the highest digit) is never 0, unless the whole list is [0]

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Copy into arraysO(m + n)
  2. One pass with a carryO(max(m, n))

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for two 100-digit listsVerdict
Copy into arraysO(m + n)
Passes; extra copies
One pass with a carryO(max(m, n))
Best; one walk, no copies

m and n = number of nodes in l1 and l2.

Edge cases to test

  • Carry at the very end. [9, 9] + [1] gives [0, 0, 1]: the loop must run once more just for the carry.
  • Different lengths. [0] + [4, 1]: once a list runs out, use 0 for its digit.
  • Both zero. [0] + [0] is [0], one node, not an empty list.
  • A carry that ripples. [1] + [9, 9, 9, 9] is [0, 0, 0, 0, 1]: the carry moves through every column.
  • Longest input. Two lists of 100 nines: far past any built-in integer, so converting to a number only works in Python.

Common mistakes

  • Converting each list to an integer: it overflows after about 19 digits.
  • Stopping when both lists end and losing the last carry.
  • Reading l1.val or l1.next after l1 is already null when the lists have different lengths.

How to talk through it

  1. 1Clarify. Is the lowest digit first? Can the lists have different lengths? Should I build a new list rather than change the inputs?
  2. 2Rule out conversion. Say that 100 digits overflow a 64-bit integer, so you will add digit by digit.
  3. 3Notice the order. Lowest digit first is the order you add by hand, so a single walk over both lists is enough.
  4. 4Code the loop. Use a dummy head, treat a finished list as 0, and keep looping while the carry is not 0.
  5. 5Test out loud. Run 99 + 1 and two lists of different lengths before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?