Given a non-negative integer c
, determine whether there exist two integers a
and b
such that a^2 + b^2 = c
.
Example 1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3
Output: false
Constraints:
0 <= c <= 2^31 - 1
Given a non-negative integer c
, we need to determine if there exist two integers a
and b
such that a^2 + b^2 = c
.
A simple approach is to iterate through all possible values of a
from 0 up to the square root of c
. For each a
, we can calculate b^2 = c - a^2
. Then, we check if b
is an integer by taking the square root of b^2
and verifying if it's an integer.
import math
def judgeSquareSum_brute_force(c: int) -> bool:
for a in range(int(math.sqrt(c)) + 1):
b_squared = c - a * a
if b_squared >= 0:
b = math.sqrt(b_squared)
if b == int(b):
return True
return False
O(sqrt(c)), as we iterate up to the square root of c
.
O(1), as we use only a constant amount of extra space.
A more efficient approach uses the two-pointer technique. We initialize two pointers, left
and right
. left
starts at 0, and right
starts at the square root of c
. We then iterate while left <= right
. In each iteration, we calculate a^2 + b^2
(where a
is left
and b
is right
).
c
, we've found a solution, and return True
.c
, we increment left
to increase the sum.c
, we decrement right
to decrease the sum.If we complete the loop without finding a solution, we return False
.
import math
def judgeSquareSum(c: int) -> bool:
left = 0
right = int(math.sqrt(c))
while left <= right:
sum_of_squares = left * left + right * right
if sum_of_squares == c:
return True
elif sum_of_squares < c:
left += 1
else:
right -= 1
return False
O(sqrt(c)), as the two pointers can move at most sqrt(c) times.
O(1), as we use only a constant amount of extra space.
a = 0
and b = 0
is a valid solution.a = 1
and b = 0
(or vice versa) is a valid solution.c
without integer overflow issues.