File: find-the-pivot-integer/solution.py

Date: 2026-06-06

Time: 16:48

Purpose

This file solves LeetCode 2485: Find the Pivot Integer. It finds an integer x in [1, n] where the sum of all integers from 1 to x equals the sum from x to n. It exports a single function find_pivot used by the corresponding test file.

Key Components

find_pivot(n: int) -> int

The only function. Takes a positive integer n and returns the pivot x, or -1 if none exists.

The key insight is algebraic. The pivot condition is:


sum(1..x) == sum(x..n)

Both sides include x, so expanding:


x*(x+1)/2 == x + (x+1) + ... + n = n*(n+1)/2 - x*(x-1)/2

Simplifying yields x^2 = n*(n+1)/2. So the pivot exists if and only if the triangular number T(n) = n*(n+1)/2 is a perfect square.

Patterns

Closed-form math instead of iteration. Rather than looping through candidates or maintaining prefix sums, the solution reduces to a single formula evaluation. This is O(1) time and space — the best you can do for this problem.

isqrt for exact integer square root checking. The pattern x = isqrt(total); x * x == total is the canonical way to test perfect squares in Python without floating-point precision issues. math.isqrt returns the floor of the exact square root, so the round-trip check is exact.

Dependencies

Imports: math.isqrt — Python's integer square root (available since 3.8). No project-internal dependencies.

Imported by: find-the-pivot-integer/testsolution.py directly. The massive "Imported By" list in the context is noise — those are test files for *other* problems that happen to share a test harness pattern; they don't actually call findpivot.

Flow

1. Compute total = n*(n+1) // 2 — the sum of integers 1 through n.

2. Compute x = isqrt(total) — the largest integer whose square is ≤ total.

3. If x * x == total, then x is the pivot. Return it.

4. Otherwise, no pivot exists. Return -1.

No loops, no branching beyond the single if.

Invariants

Error Handling

None. The function assumes valid input and has no failure modes beyond the "not found" case, which it signals with -1 (the LeetCode convention).

Topics to Explore

Beliefs