File: add-to-array-form-of-integer/solution.py

Date: 2026-06-06

Time: 15:13

Purpose

This file solves LeetCode 989: Add to Array-Form of Integer. It takes a number represented as an array of digits (num) and adds an integer k to it, returning the result as an array of digits. The file is self-contained: solution class + unit tests in one module.

Key Components

Solution.addToArrayForm(num, k) -> List[int]

The core method. It performs digit-by-digit addition from right to left, using k itself as both the addend and the carry accumulator.

Contract: num is a non-empty list of single digits representing a non-negative integer (most significant digit first). k is a non-negative integer. Returns a list of digits representing num + k.

TestAddToArrayForm

Seven test cases covering: basic addition, carry propagation, single-digit arrays, full carry overflow (999 + 1 = 1000), zero array, and k being much larger than num.

Patterns

In-place mutation with extension: The algorithm modifies num in place for existing positions, and uses list.insert(0, ...) to prepend digits when k has more digits than num. This avoids allocating a separate result array for the common case where no new digits are needed.

Carry absorption into k: Instead of maintaining a separate carry variable, the algorithm folds the carry into k via k //= 10. This is the key trick — k starts as the number to add, and after each iteration it becomes the remaining value plus any carry. The loop condition while i >= 0 or k naturally handles both traversing num and draining any remaining carry/digits from k.

Flow

1. Start at the least significant digit (i = len(num) - 1).

2. Each iteration:

3. Loop exits when both i < 0 (array exhausted) and k == 0 (no remaining digits/carry).

4. Return the modified num.

Invariants

Error Handling

None. The solution trusts LeetCode's input constraints (valid digit array, non-negative k). No validation, no exceptions. The tests use assertEqual assertions — failures surface as unittest errors.

Dependencies

Imports: typing.List (type annotation), unittest (tests).

Imported by: The "Imported By" list in the prompt is misleading — those are unrelated test files across the repo that happen to import unittest, not files that import this solution. The actual dependent is add-to-array-form-of-integer/test_solution.py.

Topics to Explore

Beliefs