DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 2: Add Two Numbers — Step-by-Step Visual Trace

Medium — Linked List | Math | Simulation

The Problem

Given two non-empty linked lists representing two non-negative integers stored in reverse order, add the two numbers and return the sum as a linked list.

Approach

Traverse both linked lists simultaneously, adding corresponding digits along with any carry from the previous addition. Create a new linked list to store the result, handling cases where lists have different lengths and managing the final carry.

Time: O(max(m, n)) · Space: O(max(m, n))

Code

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode()
        current = dummy
        carry = 0

        while l1 or l2:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            total = val1 + val2 + carry

            carry = total // 10
            digit = total % 10

            current.next = ListNode(digit)
            current = current.next

            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        if carry:
            current.next = ListNode(carry)

        return dummy.next
Enter fullscreen mode Exit fullscreen mode

Watch It Run

TraceLit — See exactly where your code breaks

Paste your LeetCode solution and see every pointer, variable, and data structure update step by step.

favicon tracelit.dev

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)