633. Sum of Square Numbers LeetCode Solution

In this guide, you will get 633. Sum of Square Numbers LeetCode Solution with the best time and space complexity. The solution to Sum of Square Numbers problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum of Square Numbers solution in C++
  4. Sum of Square Numbers solution in Java
  5. Sum of Square Numbers solution in Python
  6. Additional Resources
633. Sum of Square Numbers LeetCode Solution image

Problem Statement of Sum of Square Numbers

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

Complexity Analysis

  • Time Complexity: O(\sqrt{c})
  • Space Complexity: O(1)

633. Sum of Square Numbers LeetCode Solution in C++

class Solution {
 public:
  bool judgeSquareSum(int c) {
    unsigned l = 0;
    unsigned r = sqrt(c);

    while (l <= r) {
      const unsigned sum = l * l + r * r;
      if (sum == c)
        return true;
      if (sum < c)
        ++l;
      else
        --r;
    }

    return false;
  }
};
/* code provided by PROGIEZ */

633. Sum of Square Numbers LeetCode Solution in Java

class Solution {
  public boolean judgeSquareSum(int c) {
    int l = 0;
    int r = (int) Math.sqrt(c);

    while (l <= r) {
      final int sum = l * l + r * r;
      if (sum == c)
        return true;
      if (sum < c)
        ++l;
      else
        --r;
    }

    return false;
  }
}
// code provided by PROGIEZ

633. Sum of Square Numbers LeetCode Solution in Python

class Solution:
  def judgeSquareSum(self, c: int) -> bool:
    l = 0
    r = math.isqrt(c)

    while l <= r:
      summ = l * l + r * r
      if summ == c:
        return True
      if summ < c:
        l += 1
      else:
        r -= 1

    return False
# code by PROGIEZ

Additional Resources

See also  854. K-Similar Strings LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.