Leetcode #633: Sum of Square Numbers
In this guide, we solve Leetcode #633 Sum of Square Numbers in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Two Pointers, Binary Search
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Python Solution
class Solution:
def judgeSquareSum(self, c: int) -> bool:
a, b = 0, int(sqrt(c))
while a <= b:
s = a**2 + b**2
if s == c:
return True
if s < c:
a += 1
else:
b -= 1
return False
Complexity
The time complexity is , where is the given non-negative integer. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.