Count Square Sum Triples - Problem
Square Sum Triples - The Classic Pythagorean Problem

A square triple (a, b, c) is a set of three integers where a² + b² = c². These are also known as Pythagorean triples, named after the famous theorem about right triangles!

Given an integer n, your task is to count how many square triples exist where all three numbers a, b, and c are between 1 and n (inclusive).

Examples:
• For n=5: The triple (3, 4, 5) works because 3² + 4² = 9 + 16 = 25 = 5²
• For n=10: We can find triples like (3, 4, 5), (4, 3, 5), (6, 8, 10), (8, 6, 10)

Note: Order matters! (3, 4, 5) and (4, 3, 5) are considered different triples.

Input & Output

example_1.py — Basic Case
$ Input: n = 5
Output: 2
💡 Note: There are 2 square triples: (3,4,5) because 3² + 4² = 9 + 16 = 25 = 5², and (4,3,5) because 4² + 3² = 16 + 9 = 25 = 5². Note that (3,4,5) and (4,3,5) are counted as different triples.
example_2.py — Larger Range
$ Input: n = 10
Output: 4
💡 Note: There are 4 square triples: (3,4,5), (4,3,5), (6,8,10), and (8,6,10). The first two come from the 3-4-5 Pythagorean triple, and the last two come from the 6-8-10 triple (which is 2 times the 3-4-5 triple).
example_3.py — Edge Case
$ Input: n = 2
Output: 0
💡 Note: No square triples exist with all values ≤ 2. The smallest Pythagorean triple is (3,4,5), which requires n ≥ 5.

Visualization

Tap to expand
Finding Pythagorean Triplesa = 3b = 4c = 5Perfect Squares Set{1, 4, 9,25,36, 49, ...}3² + 4² = 9 + 16 = 25 ✓25 is in our set!Algorithm Steps1. Store all i² (i=1 to n)2. For each pair (a,b):• Calculate sum = a² + b²• Check if sum ∈ squares• If yes, count++Example: n=5 gives us 2 triples: (3,4,5) and (4,3,5)🎯 Key InsightInstead of checking if √(a² + b²) is an integer,we check if (a² + b²) exists in our pre-computed perfect squares!
Understanding the Visualization
1
Setup Perfect Squares
Pre-compute all squares 1², 2², 3², ..., n² for quick lookup
2
Test All Pairs
For each possible pair (a,b), calculate what the hypotenuse c would need to be
3
Verify Triangle
Check if c² = a² + b² exists in our set of perfect squares and c ≤ n
Key Takeaway
🎯 Key Insight: Pre-computing perfect squares and using hash lookup transforms an O(n³) brute force into an elegant O(n²) solution with O(1) verification per pair.

Time & Space Complexity

Time Complexity
⏱️
O(n²)

Two nested loops with O(1) hash set lookup for each pair

n
2n
Quadratic Growth
Space Complexity
O(n)

Hash set stores up to n perfect squares

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 250
  • All values a, b, c must be in range [1, n]
  • Order matters: (3,4,5) and (4,3,5) are different triples
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen