Hide sidebar

Add Two Numbers

Linked ListMath
MediumLeetCode #2
20-25 min

Problem Statement

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

Example

Example 1:
2
4
3
+
5
6
4
=
7
0
8

Explanation: 342 + 465 = 807.

Constraints

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

Solution

Approach: Elementary Math

This problem can be solved by simulating the process of manual addition, column by column, while keeping track of a carry-over value.

2
4
3
+
5
6
4
=
Step 0

Algorithm Steps

  • Initialize a dummy head for the result list and a `carry` variable to 0.
  • Traverse both input lists simultaneously.
  • At each step, calculate the sum of the current digits from both lists and the carry.
  • The new digit for the result list is `sum % 10`, and the new carry is `sum / 10`.
  • Create a new node with the calculated digit and append it to the result list.
  • If a carry remains after the lists are fully traversed, add a final node for the carry.
Elementary Math Solution

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # Dummy node to serve as the head of the result list.
        dummy = ListNode()
        curr = dummy
        carry = 0

        # Loop until both lists are exhausted and there's no carry.
        while l1 or l2 or carry:
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0

            # Calculate the new digit and carry.
            val = v1 + v2 + carry
            carry = val // 10
            val = val % 10
            curr.next = ListNode(val)

            # Move to the next nodes.
            curr = curr.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
            
        return dummy.next