SDE & MLE Prep

2. Add Two Numbers

Problem

Two non-empty linked lists hold non-negative integers with their digits in reverse order (ones digit first). Return their sum as a linked list in the same format.

Example: 2→4→3 + 5→6→4 → 7→0→8 (342 + 465 = 807)

Digits are stored least-significant first, so add node by node with a carry, like grade-school addition.

  2 -> 4 -> 3     (342)
+ 5 -> 6 -> 4     (465)
= 7 -> 0 -> 8     (807)   carry: 0, 1, 0

Complexity: O(max(m, n)).

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = tail = ListNode()
        carry = 0
        while l1 or l2 or carry:
            s = carry + (l1.val if l1 else 0) + (l2.val if l2 else 0)
            carry, d = divmod(s, 10)
            tail.next = ListNode(d)
            tail = tail.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next