Given a non-negative integer c
, determine whether there are two integers a
and b
such that:
[ a^2 + b^2 = c ]
a
and b
be the same number?
a
and b
can be the same or different as long as ( a^2 + b^2 = c ).c
?
c
is a non-negative integer and can range from 0 to ( 2^{31} - 1 ).a
and b
?
To solve the problem efficiently, we can use the following approach:
a
starting at 0.b
starting at ( \sqrt{c} ).True
.a
to increase the sum.b
to decrease the sum.False
.Here’s the code implementing the above strategy:
import math
def judgeSquareSum(c):
# Initialize pointers
a = 0
b = int(math.sqrt(c))
while a <= b:
current_sum = a * a + b * b
if current_sum == c:
return True # Found the integers a and b such that a^2 + b^2 = c
elif current_sum < c:
a += 1 # Increase the sum by increasing a
else:
b -= 1 # Decrease the sum by decreasing b
return False # No such integers found
# Example usage:
c = 5
print(judgeSquareSum(c)) # Output: True, since 1^2 + 2^2 = 5
The time complexity of this approach is ( O(\sqrt{c}) ) because in the worst case, the a
pointer will iterate from 0 to ( \sqrt{c} ), and the b
pointer will iterate from ( \sqrt{c} ) back down to 0.
The space complexity is ( O(1) ) because we are using a constant amount of extra space regardless of the input size.
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?