Task example: Add Two Numbers

Two nonempty linked lists represent nonnegative integers. Each node holds one digit, with the ones digit first. Return a new linked list representing their sum in the same reverse-digit order.

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

342 + 465 = 807. The nodes store digits in reverse order.

Example 2
Input
l1 = [9,9]
l2 = [1]
Output
[0,0,1]

99 + 1 = 100. The final carry needs one more node.

Each input has 1 to 100 nodes, with digits from 0 to 9. The last digit cannot be zero unless the entire number is zero. Inputs stay unchanged.

LeetCode 2 ↗
01 / Copy digits into arrays

Copy digits: video explanation

l1 = [2,4,3]
l2 = [5,6,4]
output: [7,0,8]

Prefer reading? Follow the steps below.

  1. Copy the digits of each input list into an array. Set an index and carry to zero, and create a dummy node to build the answer.
  2. At each index, add both digits and the incoming carry. A missing digit counts as zero. divmod(total, 10) gives the next carry and the digit to append.
  3. Append a new node, advance the index, and continue while any digits or carry remain. Return dummy.next, skipping the dummy node.

Time complexity · O(m + n)

For input lengths m and n, copying and adding digits takes O(m + n) time.

Space complexity · O(m + n) auxiliary

The copied arrays use O(m + n) auxiliary space. The returned list separately uses O(max(m, n)) space, with at most one extra carry node.

PYTHONLive code trace
02 / Direct addition - optimal auxiliary space

Direct addition: video explanation

l1 = [2,4,3]
l2 = [5,6,4]
output: [7,0,8]

Prefer reading? Follow the steps below.

  1. Start from both heads with carry = 0. Because digits are reversed, the heads already contain the ones digits.
  2. Add the current digits and carry. Use zero for an exhausted list. Append the remainder after division by 10, and keep the quotient as the next carry.
  3. Advance each existing input node. Keep going while either list or carry remains, so a final carry becomes a new node. Return dummy.next.

Both approaches are linear-time. Direct addition avoids copying input digits, reducing auxiliary space from O(m + n) to O(1). The output list still requires space.

Time complexity · O(m + n)

Each input node is visited once. For lengths m and n, time complexity is O(m + n).

Space complexity · O(1) auxiliary

O(1) auxiliary space for references, digits, and carry. Excluding auxiliary space, the returned list uses O(max(m, n)) space.

PYTHONLive code trace

Add Two Numbers · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.