Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

633. Sum of Square Numbers

Explanation:

To solve this problem, we can use a two-pointer approach. We initialize two pointers, left at 0 and right at the square root of c. At each step, we calculate the sum of the squares of the values at these pointers. If the sum is equal to c, we return true. If the sum is less than c, we increment the left pointer to increase the sum, and if the sum is greater than c, we decrement the right pointer to decrease the sum. We continue this process until left is less than or equal to right.

Time complexity: O(sqrt(c)) Space complexity: O(1)

:

class Solution {
    public boolean judgeSquareSum(int c) {
        int left = 0, right = (int)Math.sqrt(c);
        while (left <= right) {
            int sum = left*left + right*right;
            if (sum == c) {
                return true;
            } else if (sum < c) {
                left++;
            } else {
                right--;
            }
        }
        return false;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.