#1925
Count Square Sum Triples
EasyMathEnumerationMathematical EnumerationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n√n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n√n)Space O(1)
Instead of checking every pair (a, b), we can iterate through possible values of c and find pairs (a, b) that satisfy the equation a² + b² = c². This reduces the number of iterations significantly.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Iterate over all values of c from 1 to n.
- 3Step 3: For each c, iterate over possible values of a from 1 to c (since a must be less than or equal to c).
- 4Step 4: Calculate b as sqrt(c² - a²).
- 5Step 5: Check if b is an integer and if b <= n. If true, increment the counter.
- 6Step 6: Return the counter.
solution.py14 lines
1# Full working Python code
2import math
3
4def countSquareSumTriples(n):
5 count = 0
6 for c in range(1, n + 1):
7 for a in range(1, c + 1):
8 b = math.sqrt(c * c - a * a)
9 if b.is_integer() and b <= n:
10 count += 1
11 return count
12
13# Example usage
14print(countSquareSumTriples(5)) # Output: 2ℹ
Complexity note: The time complexity is O(n√n) because for each value of c, we iterate up to c, and calculating b involves a square root operation. The space complexity is O(1) since we are using a constant amount of space.
- 1Square triples are symmetric; (a, b, c) and (b, a, c) count as separate valid triples.
- 2The maximum value of c determines the range of possible a and b values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.