Add Two Numbers

interview_workbook/leetcode/linked_list /app/src/interview_workbook/leetcode/linked_list/add_two_numbers.py
View Source

Algorithm Notes

Summary: Add Two Numbers — notes not yet curated.
Time: Estimate via loops/recurrences; common classes: O(1), O(log n), O(n), O(n log n), O(n^2)
Space: Count auxiliary structures and recursion depth.
Tip: See the Big-O Guide for how to derive bounds and compare trade-offs.

Big-O Guide

Source

"""
Add Two Numbers

Problem: Add Two Numbers
LeetCode link: https://leetcode.com/problems/add-two-numbers/
Description: Add two numbers represented as linked lists and return head of result list.
"""

from src.interview_workbook.leetcode._nodes import ListNode
from src.interview_workbook.leetcode._registry import register_problem
from src.interview_workbook.leetcode._types import Category, Difficulty


class Solution:
    def solve(self, *args):
        """
        Add two numbers represented by linked lists.
        Args: l1, l2 (ListNode)
        Returns: ListNode (head of result list)
        """
        l1, l2 = args
        dummy = ListNode(0)
        curr = dummy
        carry = 0
        while l1 or l2 or carry:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            s = val1 + val2 + carry
            carry = s // 10
            curr.next = ListNode(s % 10)
            curr = curr.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next


def demo():
    """Run a simple demonstration for Add Two Numbers problem."""
    from src.interview_workbook.leetcode._nodes import ListNode

    def build_list(nums):
        dummy = ListNode(0)
        curr = dummy
        for n in nums:
            curr.next = ListNode(n)
            curr = curr.next
        return dummy.next

    def list_to_str(node):
        vals = []
        while node:
            vals.append(str(node.val))
            node = node.next
        return "->".join(vals)

    s = Solution()
    l1 = build_list([2, 4, 3])  # represents 342
    l2 = build_list([5, 6, 4])  # represents 465
    result = s.solve(l1, l2)  # should represent 807 -> [7,0,8]
    return f"243 + 564 -> {list_to_str(result)}"


register_problem(
    id=2,
    slug="add_two_numbers",
    title="Add Two Numbers",
    category=Category.LINKED_LIST,
    difficulty=Difficulty.MEDIUM,
    tags=["linked_list", "math"],
    url="https://leetcode.com/problems/add-two-numbers/",
    notes="",
)