Leetcode 1925. Count Square Sum Triples
Given a positive integer n
, you need to return the number of triplets (a, b, c)
such that:
1 <= a, b, c <= n
a^2 + b^2 = c^2
(a, b, c)
be unique, meaning (a, b, c)
is considered the same as (b, a, c)
?
(a, b)
doesn’t matter unless otherwise stated.a
, b
, and c
need to be distinct?
a
and b
are usually allowed to be the same, but we should confirm to avoid ambiguity.To solve the problem, we can iterate through all possible values of a
and b
within the range [1, n]
, and then check if c = sqrt(a^2 + b^2)
(where c
also needs to be an integer and within the range). If c
falls within the range [1, n]
, then (a, b, c)
is a valid triplet.
Here is a possible implementation in Java:
public class Solution {
public int countTriples(int n) {
int count = 0;
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
int cSquared = a * a + b * b;
int c = (int) Math.sqrt(cSquared);
// Check if c is an integer and within the range [1, n]
if (c <= n && c * c == cSquared) {
count++;
}
}
}
return count;
}
}
a
and b
:
(a, b)
such that both a
and b
lie within [1, n]
.cSquared
as a^2 + b^2
.c
as the integer square root of cSquared
.c
squared is equal to cSquared
and if c
lies within [1, n]
.a
and b
) is O(n^2)
.Math.sqrt
is O(1)
since it operates in constant time.O(n^2)
time.This solution is efficient enough for the given constraints of the problem.
Would you like us to explore any other aspects or optimize further?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?