SDE & MLE Prep

445. Add Two Numbers II

Problem

Two non-empty linked lists hold non-negative integers with the most significant digit first. Return their sum as a linked list in the same order.

Example: 7→2→4→3 + 5→6→4 → 7→8→0→7 (7243 + 564)

Constraints: follow-up: without reversing the input lists.

Most-significant digit first → push both lists' digits onto stacks, pop and add from the least significant, prepending each result node.

Complexity: O(m + n).

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