File: count-square-sum-triples/solution.py

Date: 2026-06-06

Time: 16:04

count-square-sum-triples/solution.py

Purpose

Solves LeetCode 1925 — Count Square Sum Triples. Given an integer n, count the number of ordered triples (a, b, c) where 1 <= a, b, c <= n and a² + b² = c² (Pythagorean triples). The triple is ordered, so (3, 4, 5) and (4, 3, 5) are both counted.

Key Components

Solution.countTriples(self, n: int) -> int — the single method. Takes an upper bound n, returns the count of valid ordered Pythagorean triples.

Patterns

Hash-set lookup for O(1) membership testing. Instead of a third nested loop over c, the solution precomputes squares = {i * i for i in range(1, n + 1)} — the set of all perfect squares up to . Then for each (a, b) pair, it checks a² + b² against this set in constant time, reducing what would be O(n³) to O(n²).

This is the standard "enumerate two dimensions, look up the third" pattern you see across many LeetCode solutions involving triplet constraints.

Dependencies

Imports: None — pure standard library, no external dependencies.

Imported by: The count-square-sum-triples/test_solution.py file imports this class. The massive "Imported By" list in the prompt is a red herring — those are unrelated test files that happen to share the same import pattern (from solution import Solution) via relative imports in their own directories, not actual imports of *this* file.

Flow

1. Build a set of all perfect squares from to .

2. Enumerate all (a, b) pairs where 1 <= a, b <= n (both orderings).

3. Compute s = a² + b². If s is in the precomputed set, that means some c in [1, n] satisfies c² = s, so increment the count.

4. Return the total count.

The key insight: checking s in squares implicitly validates c <= n because the set only contains squares of values up to n.

Invariants

Error Handling

None. The method assumes valid input per LeetCode constraints (1 <= n <= 250). No edge-case guards for n = 0 or negative values.

Complexity

For the constraint n <= 250, this gives at most 62,500 iterations — trivially fast.

Topics to Explore

Beliefs