#2

Add Two Numbers

Medium
Linked ListMathRecursionHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Iterative)
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses an iterative method to add the two numbers digit by digit, taking care of the carry. This avoids the overhead of converting to and from integers, making it more efficient in both time and space.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a dummy head for the result linked list and a carry variable set to 0.
  2. 2Step 2: While both linked lists are not empty, extract the values and add them along with the carry.
  3. 3Step 3: Calculate the new digit (sum % 10) and update the carry (sum // 10).
  4. 4Step 4: Create a new node with the new digit and attach it to the result list.
  5. 5Step 5: Move to the next nodes in both linked lists.
  6. 6Step 6: If there's a carry left after processing both lists, add a new node with the carry.
solution.py26 lines
1# Full working Python code with comments
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7class Solution:
8    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
9        dummy_head = ListNode(0)
10        current = dummy_head
11        carry = 0
12
13        while l1 or l2 or carry:
14            val1 = l1.val if l1 else 0
15            val2 = l2.val if l2 else 0
16            total = val1 + val2 + carry
17            carry = total // 10
18            current.next = ListNode(total % 10)
19            current = current.next
20
21            if l1:
22                l1 = l1.next
23            if l2:
24                l2 = l2.next
25
26        return dummy_head.next

Complexity note: The time complexity is O(n) because we traverse both linked lists once, and the space complexity is O(1) because we are using a constant amount of space for the carry and the result list nodes are created in place.

  • 1The key observation is that the linked lists represent numbers in reverse order, allowing us to add them digit by digit directly.
  • 2Another important insight is that we can handle carry values during addition, similar to how we add numbers on paper.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.