#445

Add Two Numbers II

Medium
Linked ListMathStackStackTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses stacks to reverse the order of the digits and then adds them together. This avoids the need for converting the entire linked list into a number, making it more efficient and straightforward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use two stacks to store the digits of both linked lists.
  2. 2Step 2: Pop the digits from the stacks and add them together, keeping track of the carry.
  3. 3Step 3: Construct the resulting linked list from the sum, ensuring to handle any remaining carry.
solution.py27 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def addTwoNumbers(l1, l2):
8    stack1, stack2 = [], []
9    while l1:
10        stack1.append(l1.val)
11        l1 = l1.next
12    while l2:
13        stack2.append(l2.val)
14        l2 = l2.next
15    carry = 0
16    dummy = ListNode()
17    while stack1 or stack2 or carry:
18        sum = carry
19        if stack1:
20            sum += stack1.pop()
21        if stack2:
22            sum += stack2.pop()
23        carry = sum // 10
24        new_node = ListNode(sum % 10)
25        new_node.next = dummy.next
26        dummy.next = new_node
27    return dummy.next

Complexity note: The time complexity is O(n) because we traverse each linked list once. The space complexity is O(n) due to the stacks used to store the digits.

  • 1Using stacks allows us to reverse the order of digits easily.
  • 2Handling carry is crucial when adding the digits.

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