633. Sum of Square Numbers
Difficulty: Medium
Topics: Math
, Two Pointers
, Binary Search
Given a non-negative integer c
, decide whether there're two integers a
and b
such that a2 + b2 = c
.
Example 1:
- Input: c = 5
- Output: true
- Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
- Input: c = 3
- Output: false
Constraints:
0 <= c <= 231 - 1
Solution:
We can utilize a two-pointer approach. Here's how we can approach the problem:
Explanation:
-
Constraints:
- We're given a non-negative integer
c
. - We need to find two integers
a
andb
such thata² + b² = c
.
- We're given a non-negative integer
-
Two-pointer Approach:
- Start with two pointers:
a
initialized to 0, andb
initialized to the square root ofc
. - The idea is to check the sum of the squares of
a
andb
. Ifa² + b²
equalsc
, returntrue
. - If
a² + b²
is less thanc
, incrementa
to increase the sum. - If
a² + b²
is greater thanc
, decrementb
to decrease the sum. - Continue this process until
a
is less than or equal tob
. - If no such pair is found, return
false
.
- Start with two pointers:
Let's implement this solution in PHP: 633. Sum of Square Numbers
<?php
/**
* @param Integer $c
* @return Boolean
*/
function judgeSquareSum($c) {
...
...
...
/**
* go to ./solution.php
*/
}
// Example usage:
$c1 = 5;
$c2 = 3;
echo "Result for c = $c1: " . (judgeSquareSum($c1) ? "true" : "false") . "\n"; // Output: true
echo "Result for c = $c2: " . (judgeSquareSum($c2) ? "true" : "false") . "\n"; // Output: false
?>
Explanation:
-
Initialization:
-
$a = 0
: The left pointer starts from 0. -
$b = (int) sqrt($c)
: The right pointer starts from the integer value of the square root ofc
, asb²
cannot exceedc
.
-
-
Loop:
- The loop continues as long as
a <= b
. - If
a² + b²
equalsc
, the function returnstrue
. - If
a² + b²
is less thanc
, it means we need a larger sum, so we incrementa
. - If
a² + b²
is greater thanc
, we need a smaller sum, so we decrementb
.
- The loop continues as long as
-
End Condition:
- If no such integers
a
andb
are found, returnfalse
.
- If no such integers
Time Complexity:
- The time complexity is
O(sqrt(c))
because we iterate through the integers from0
tosqrt(c)
.
Example Outputs:
- For
c = 5
, the function will returntrue
because1² + 2² = 5
. - For
c = 3
, the function will returnfalse
because no integers satisfy the equationa² + b² = 3
.
This approach efficiently checks for two integers whose squares sum up to c
using a two-pointer technique.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Top comments (0)