Problem Description
Given a non-negative integer c, decide whether there exist two integers a and b such that a² + b² = c.
Key Insights
- Use a two-pointer approach where one pointer (a) starts from 0 and the other pointer (b) starts from the integer square root of c.
- At each step, compute the sum of squares (a² + b²) and compare it with c.
- If the sum is less than c, increment a to get a larger value; if the sum is greater than c, decrement b to get a smaller value.
- Continue until the pointers meet. If a valid pair is found, return true; otherwise, return false.
Space and Time Complexity
Time Complexity: O(√c) - In the worst-case scenario, both pointers traverse the number line up to the square root of c. Space Complexity: O(1) - Only constant extra space is used.
Solution
The solution uses a two-pointer technique with one pointer (a) starting at 0 and the other pointer (b) starting at the floor of √c. We iterate using the following logic:
- Calculate the sum of squares: currentSum = a² + b².
- If currentSum equals c, a valid pair (a, b) is found and the function returns true.
- If currentSum is less than c, increment a to increase the sum.
- If currentSum is greater than c, decrement b to decrease the sum.
- Repeat the process until a > b. If no pair is found, return false. This method ensures an efficient search with minimal iterations.