Skip to content
LEETFLIX

Medium · digit-wise add with carry. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 2. Add Two Numbers. The copyrighted prompt is on LeetCode. This page is a working digit-wise add with carry for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

l1 =
[2, 4, 3]
l2 =
[5, 6, 4]

Output

[7, 0, 8]

342 + 465 = 807, written least-significant digit first.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Walk both lists, add, propagate carry

Each node is one digit, least-significant first. Add the two digits plus carry, emit sum % 10, keep sum // 10 as the next carry.

The lists already store the number backwards, so you can add from the heads the way you add on paper from the right. A leftover carry becomes one extra node.

Algorithm

  1. Start at both heads with carry = 0.
  2. While either list or the carry remains: add digits + carry, append sum % 10, set carry = sum // 10.
  3. Return the built list.
Time
O(max(n, m))
Space
O(max(n, m))
Solution.py
class Solution:    def addTwoNumbers(self, l1: list[int], l2: list[int]) -> list[int]:        out: list[int] = []        carry = 0        i = 0        while i < len(l1) or i < len(l2) or carry:            a = l1[i] if i < len(l1) else 0            b = l2[i] if i < len(l2) else 0            total = a + b + carry            out.append(total % 10)            carry = total // 10            i += 1        return out
Watch this run

03

Interactive walkthrough

Playing “Walk both lists, add, propagate carry”. Edit the input, hit Run, then scrub.

Approach: Walk both lists, add, propagate carry

Loading animation…