File: add-strings/solution.py

Date: 2026-06-06

Time: 15:12

add-strings/solution.py

Purpose

This file solves LeetCode 415: Add Strings. It implements arbitrary-precision addition of two non-negative integers represented as strings, without converting them to integers or using built-in big-integer libraries. This is the kind of constraint you'd see in an interview — the point is to simulate grade-school column addition manually.

Key Components

Solution.addStrings(num1: str, num2: str) -> str — The only method. Takes two digit strings, returns their sum as a digit string. No mutation of inputs.

Flow

The algorithm walks both strings from right to left (least significant digit first), exactly like you'd add numbers by hand:

1. Initialize two pointers i, j at the last index of each string, plus a carry accumulator.

2. Loop while there are digits remaining in either string OR there's a carry to propagate.

3. Extract digits using ord(char) - 48 — converting ASCII to integer without int(). If a pointer has gone past the beginning of its string, that digit is 0.

4. Compute total = d1 + d2 + carry, then divmod(total, 10) splits it into the new carry and the current digit.

5. Append the digit (converted back via chr(digit + 48)) to a result list.

6. Reverse the result list at the end, since digits were accumulated in reverse order.

Patterns

Dependencies

Imports: None. Pure standard library, no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are test files across the entire repo that happen to follow a common import pattern. The actual consumer is add-strings/test_solution.py, which tests this solution. The rest are unrelated test files that import their own respective solutions.

Invariants

Error Handling

None. The code assumes well-formed input per the LeetCode contract. Passing non-digit characters, empty strings, or negative numbers would produce garbage or crash on index access.

Topics to Explore

Beliefs