Count Square Sum Triples Problem
#1925
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1925.
A square triple (a,b,c) is a triple where a, b, and c are integers and a^2 + b^2 = c^2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
Constraints:
1 <= n <= 250
Solution
Approach: Enumeration
Try every pair a, b with 1 <= a, b < n, compute c = sqrt(a*a + b*b), and count the pair if c is an integer and c <= n. Ordered pairs are counted, which matches the problem ((3,4,5) and (4,3,5) are different triples).
Complexity: O(n2) time and O(1) space.
from math import sqrt
class Solution:
def countTriples(self, n: int) -> int:
ans = 0
for a in range(1, n):
for b in range(1, n):
x = a * a + b * b
c = int(sqrt(x))
if c <= n and c * c == x:
ans += 1
return ans