File: arranging-coins/solution.py

Date: 2026-06-06

Time: 15:15

arranging-coins/solution.py

Purpose

Solves LeetCode 441 — Arranging Coins. Given n coins, you build a staircase where row k requires exactly k coins. The function returns how many complete rows you can fill.

Key Components

arrange_coins(n: int) -> int — The sole public function. Takes a coin count and returns the number of complete staircase rows.

The implementation is a closed-form O(1) solution using the quadratic formula. The number of complete rows k satisfies:


k * (k + 1) / 2 <= n

Rearranging into a quadratic k^2 + k - 2n <= 0 and solving gives:


k = floor((-1 + sqrt(1 + 8n)) / 2)

Which is exactly what (isqrt(8 * n + 1) - 1) // 2 computes using integer arithmetic.

Patterns

Dependencies

Imports: math.isqrt (Python 3.8+) — computes the integer square root without floating-point intermediate.

Imported by: arranging-coins/test_solution.py directly. The "Imported By" list in the prompt is the full test suite across all problems — those files import their own respective solutions, not this one.

Flow

1. Compute 8 * n + 1 (the discriminant of the quadratic).

2. Take the integer square root.

3. Subtract 1 and integer-divide by 2.

4. Return the result.

Single expression, no branching, no allocation.

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. Passing n < 0 would cause isqrt to raise a ValueError.

Topics to Explore

Beliefs