Editorial for the Problem: Sum of Square Numbers
Given a non-negative integer ( c ), the task is to determine whether there exist two integers ( a ) and ( b ) such that ( a^2 + b^2 = c ).
We can solve this problem efficiently using a two-pointer technique. The idea is to use one pointer starting from 0 (let's call it low) and another pointer starting from (sqrt{c}) (let's call it high). We then check the sum of squares of the values at these two pointers.
- Initialize Two Pointers: Set
lowto 0 andhighto ( \sqrt{c} ). - Iterate and Check: While
lowis less than or equal tohigh, compute the sum of the squares oflowandhigh.- If the sum is equal to ( c ), return
true. - If the sum is less than ( c ), increment the
lowpointer to increase the sum. - If the sum is greater than ( c ), decrement the
highpointer to decrease the sum.
- If the sum is equal to ( c ), return
class Solution {
public:
bool judgeSquareSum(int c) {
int part = 0;
long long low = 0, high = sqrt(c);
while (low <= high) {
long long sumOfSquares = low * low + high * high;
if (sumOfSquares == c) {
return true;
} else if (sumOfSquares > c) {
high--;
} else {
low++;
}
}
return false;
}
};Initialization:
lowis initialized to 0.highis initialized to ( \sqrt{c} ).
Iteration:
- The
whileloop continues as long aslowis less than or equal tohigh. - In each iteration, we calculate
sumOfSquaresas ( \text{low}^2 + \text{high}^2 ).- If
sumOfSquaresis equal to ( c ), we returntrueindicating that such integers ( a ) and ( b ) exist. - If
sumOfSquaresis greater than ( c ), we decrementhighto reduce the sum. - If
sumOfSquaresis less than ( c ), we incrementlowto increase the sum.
- If
Termination:
- If the loop exits without finding any such pairs, we return
false.
Efficiency:
- The two-pointer approach iterates at most ( \sqrt{c} ) times, making the time complexity ( O(\sqrt{c}) ). This is an optimal and efficient solution for the problem.
If you found this solution helpful, please consider liking 👍 and upvoting ⬆️. Your support helps in continuing to provide high-quality solutions.
