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
aandbsuch thata² + b² = c.
- We're given a non-negative integer
-
Two-pointer Approach:
- Start with two pointers:
ainitialized to 0, andbinitialized to the square root ofc. - The idea is to check the sum of the squares of
aandb. Ifa² + b²equalsc, returntrue. - If
a² + b²is less thanc, incrementato increase the sum. - If
a² + b²is greater thanc, decrementbto decrease the sum. - Continue this process until
ais 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
aandbare found, returnfalse.
- If no such integers
Time Complexity:
- The time complexity is
O(sqrt(c))because we iterate through the integers from0tosqrt(c).
Example Outputs:
- For
c = 5, the function will returntruebecause1² + 2² = 5. - For
c = 3, the function will returnfalsebecause 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)