Python coding

Add numbers stored as digit lists

Two non-negative integers are stored as singly linked lists of digits, least significant digit first: 2 → 4 → 3 is 342. Write add_lists(a, b): return the first node of a list in the same format that holds their sum, so 2 → 4 → 3 plus 5 → 6 → 4 gives 7 → 0 → 8 (342 + 465 = 807). Neither list is empty, the lists may differ in length, and the last digit (the most significant) is never 0 except in the number 0 itself. Each ListNode has val and next.

Add digit by digit with a carry, as on paper, instead of turning the lists into Python integers. You may create new nodes for the result.

The tests call the provided run_add_lists(a_digits, b_digits), which builds both lists and returns the digits of the list you return.

  • run_add_lists([2,4,3], [5,6,4]) → [7,0,8]
  • run_add_lists([9,9,9,9,9,9,9], [9,9,9,9]) → [8,9,9,9,0,0,0,1]
  • run_add_lists([0], [0]) → [0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The lists start at the ones digit, which is where addition on paper starts too: walk both lists in one loop and build the result behind a dummy node.

Hint 2

Each step adds the two current digits (0 for a list that has ended) plus the carry, writes total % 10 and carries total // 10.

Hint 3

Keep looping while either list has nodes or the carry is not 0: 9 → 9 plus 1 needs a third digit that neither list has.

Solution and why it works
pythonO(max(n, m)) · O(1) besides the result
# --- your code ---
def add_lists(a: "ListNode", b: "ListNode") -> "ListNode":
    dummy = tail = ListNode()
    carry = 0
    while a is not None or b is not None or carry:
        total = carry
        if a is not None:
            total += a.val
            a = a.next
        if b is not None:
            total += b.val
            b = b.next
        carry, digit = divmod(total, 10)
        tail.next = ListNode(digit)
        tail = tail.next
    return dummy.next


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_values(head: ListNode | None, limit: int) -> list[int]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the result is longer than any sum of these lists: is there a cycle?")
        out.append(head.val)
        head = head.next
    return out


def run_add_lists(a_digits: list[int], b_digits: list[int]) -> list[int]:
    limit = max(len(a_digits), len(b_digits)) + 1     # a sum has at most one extra digit
    return to_values(add_lists(build_list(a_digits), build_list(b_digits)), limit)

Digits come least significant first, the order in which carries travel, so one pass works: each step adds the two current digits, or 0 once a list has ended, plus the carry, writes total % 10 and carries total // 10. Looping while a or b or carry covers lists of different lengths and the final carry (9 → 9 plus 1 needs a third node). The dummy head spares a special case for the first digit. Converting to int dodges the question: outside Python, a 64-bit integer overflows past ~19 digits.