Add Two Numbers

35 min · addTwoNumbers()

These numbers greet you backwards: the ones digit arrives first, followed by the tens, hundreds, and everything beyond.

Each of l1 and l2 is a reverse-order digit list — a chain with one decimal digit per node, next links between nodes, and its ones digit at the head. The lists represent two non-negative integers. Add them and return their sum in the same reverse-order list format.

A few ground rules:

  • Every node stores one digit from 0 through 9.
  • The head stores the ones digit, its next node stores the tens digit, and so on.
  • An input has no leading zero at its most significant end unless the entire number is the single-node list [0].
  • The answer may need one more node than either input when a final carry remains.

Constraints

  • 1 <= l1.length, l2.length <= 100
  • 0 <= Node.val <= 9
  • Neither input has a leading zero unless it represents 0.

Hints

Add where the heads already point

Because the ones digits come first, you can add in the same direction that you walk the lists. There's no reason to reverse either input.

Carry the tens

At each position, add the two available digits and the carry from the previous position. Store total % 10; carry total // 10 into the next round.

Uneven lists still line up

When one list ends, treat its missing digit as zero. Keep going while either list has a node or the carry is nonzero — that last condition creates a new leading digit when the sum grows.

Follow-up

How would your approach change if the most significant digit came first and you weren't allowed to reverse either input list?

Visible cases

Examples

Example 1

ready
Input
l1 = [
  2,
  4,
  3
]
l2 = [
  5,
  6,
  4
]
Expected
[
  7,
  0,
  8
]
Why
342 + 465 = 807, stored ones digit first

Example 2

ready
Input
l1 = [
  0
]
l2 = [
  0
]
Expected
[
  0
]
Why
zero plus zero stays the single digit zero

Example 3

ready
Input
l1 = [
  9,
  9,
  9,
  9
]
l2 = [
  1
]
Expected
[
  0,
  0,
  0,
  0,
  1
]
Why
the carry crosses every 9 and creates a new digit

Interview signal

Asked at

AmazonMicrosoftMetaAdobe
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite