Skip to content
AI360Xpert
Beta
Difficulty: MediumLinked List

Add Two Numbers

Problem in Plain English

You are given two reversed linked lists whose nodes hold single digits of two non-negative integers. Add the numbers and return the digit sum as a reversed linked list.

Problem Statement

You are given two non-empty linked lists l1 and l2 representing two non-negative integers. The digits are stored in reverse order, so the head holds the least significant digit, and each node contains a single digit.

Add the two numbers and return the sum as a linked list in the same reversed format, creating an extra node when a final carry remains.

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, except the number 0 itself.

Examples

Example 1

Input
l1 = [2,4,3], l2 = [5,6,4]
Output
[7,0,8]

The lists encode 342 and 465; their sum 807 encodes as 7 -> 0 -> 8.

Example 2

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

Zero plus zero is zero, encoded as a single node.

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]

The sum 9999999 + 9999 = 10009998 encodes reversed as [8,9,9,9,0,0,0,1].

Intuition

Each node is one decimal column: the head is the ones column, followed by tens and hundreds. In Example 1, add 2 and 5 to write 7, then add 4 and 6 to write 0 and carry 1 into the next column. Adding 3, 4 and that carry writes 8, producing [7,0,8]. The reversed storage already gives the order needed for addition; an exhausted list contributes zero and a remaining carry becomes one extra node.

Approaches

String Conversion

Solution Details

Reveal String Conversion: intuition, complexity, and code

Hints

Hint 1
Reversed storage is a gift: the heads are the ones column, so add from the heads forward like paper arithmetic.
Hint 2
Track one carry number: each column total adds both digits and the incoming carry. Write the remainder on division by 10, and carry the integer quotient forward.
Hint 3
Loop while l1, l2, or carry is nonzero, treating a missing node as 0 so uneven lengths and a final carry just work.

Edge Cases

  • Uneven lengths, such as a 7-node list plus a 4-node list, where the missing digits count as 0.
  • A leftover final carry, such as [9] + [9], which needs a brand-new trailing node holding 1.
  • Both lists holding [0], which returns a single 0 node rather than an empty list.

Common Mistakes and Interview Tips

  • Dropping the final carry by looping only while nodes remain, which loses the leading 1 in sums like 5 + 5.
  • Reading .val from a null pointer on uneven lists instead of substituting 0 for the exhausted side.
  • Converting long lists to machine integers, which overflows once the number exceeds fixed-width range.

Key Takeaway

When digits arrive least-significant first, walk once with a running carry and build the answer behind a dummy head.