LeetCode #2 – Add Two Numbers


Problem Statement

  1. Task



Understanding the Linked List Representation

  1. Reverse Order Digits


  2. Different Lengths



Core Idea: Simulate Column-wise Addition (O(n))

  1. High-Level Idea


  2. Key Implementation Pattern

  3. /**
     * Definition for singly-linked list.
     */
    class ListNode {
        val: number;
        next: ListNode | null;
    
        constructor(val?: number, next?: ListNode | null) {
            this.val  = (val === undefined ? 0    : val);
            this.next = (next === undefined ? null : next);
        }
    }
    
    function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
        const dummy = new ListNode(); // dummy head of result list
        let node = dummy;
    
        let carry = 0;
    
        // Traverse as long as there is at least one node left
        while (l1 || l2) {
            const sum =
                carry +
                (l1 ? l1.val : 0) +
                (l2 ? l2.val : 0);
    
            const digit = sum % 10;             // ones place
            carry = Math.floor(sum / 10);       // tens place (carry)
    
            node.next = new ListNode(digit);    // append new digit node
            node = node.next;
    
            l1 = l1?.next || null;              // move forward if possible
            l2 = l2?.next || null;
        }
    
        // If we still have a carry (e.g. 999 + 1 = 1000)
        if (carry !== 0) {
            node.next = new ListNode(carry);
        }
    
        return dummy.next; // real head of the result list
    }
    
    const solution1 = addTwoNumbers;
    
    export {};
    


Example Walkthrough


Step Digit from l1 Digit from l2 Previous carry sum New digit (sum % 10) New carry (sum / 10) Result list (so far)
1 (ones) 2 5 0 7 7 0 [7]
2 (tens) 4 6 0 10 0 1 [7, 0]
3 (hundreds) 3 4 1 8 8 0 [7, 0, 8]



Complexity