Sum of Square Numbers (LeetCode 633): Solution and Explanation
Decide whether a non-negative integer c can be written as a² + b² for some integers a and b. Both numbers must sit between 0 and sqrt(c), so two pointers can sweep that range from both ends.
Intuition
If a² + b² = c, then neither a nor b can be bigger than sqrt(c). So the search space is the pairs drawn from 0 .. floor(sqrt(c)), and we can assume a <= b.
Put a at 0 and b at the top. The sum a² + b² behaves like a sorted two-sum: raising a makes it bigger, lowering b makes it smaller.
If the sum is too small, b is already as large as it may be, so any pair with this a is too small: a can be discarded. If the sum is too large, a is as small as it can be, so b can be discarded. Every step throws away one candidate, and the loop stops when the pointers cross.
Approach: Two pointers on the square roots
- Set
a = 0andb = floor(sqrt(c)). - While
a <= b, computetotal = a*a + b*bin 64-bit arithmetic. - If
total == c, return true. - If
total < c, increasea; otherwise decreaseb. - If the pointers cross, no pair works: return false.
Step-by-step example
c = 5
- floor(sqrt(5)) = 2, so start with a = 0 and b = 2.
- 0² + 2² = 4, which is less than 5. b cannot grow, so a moves to 1.
- 1² + 2² = 5, exactly c. Return true.
Code: Python, Java, C++
1class Solution:
2 def judgeSquareSum(self, c: int) -> bool:
3 a, b = 0, int(c ** 0.5)
4 while a <= b:
5 total = a * a + b * b
6 if total == c:
7 return True
8 if total < c:
9 a += 1
10 else:
11 b -= 1
12 return False1class Solution {
2 public boolean judgeSquareSum(int c) {
3 long a = 0, b = (long) Math.sqrt(c);
4 while (a <= b) {
5 long total = a * a + b * b;
6 if (total == c) {
7 return true;
8 } else if (total < c) {
9 a++;
10 } else {
11 b--;
12 }
13 }
14 return false;
15 }
16}1class Solution {
2public:
3 bool judgeSquareSum(int c) {
4 long long a = 0, b = (long long) sqrt((double) c);
5 while (a <= b) {
6 long long total = a * a + b * b;
7 if (total == c) {
8 return true;
9 } else if (total < c) {
10 a++;
11 } else {
12 b--;
13 }
14 }
15 return false;
16 }
17};Time and space complexity
O(sqrt(c))
Each iteration moves a up or b down, and together they cover at most floor(sqrt(c)) + 1 values.
O(1)
Only the two pointers and the running sum are stored.
Other approaches
Check each a for a perfect square remainder (time O(sqrt(c)), space O(1))
Loop a from 0 while a² <= c, and test whether c - a² is a perfect square with an integer square root. It has the same bound and is equally short.
Binary search for b (time O(sqrt(c) log c), space O(1))
For each a, binary search b in 0 .. sqrt(c) so that b² = c - a². It works but adds a log factor for no gain.
Fermat's two-squares theorem (time O(sqrt(c)), space O(1))
c is a sum of two squares exactly when every prime of the form 4k + 3 appears to an even power in c. Factoring c by trial division also takes O(sqrt(c)) time.
Common mistakes
- Using 32-bit integers for a*a + b*b. With c near 2^31 - 1 the sum can overflow.
- Starting a at 1. Zero is allowed, so c = 4 is 0² + 2².
- Looping while a < b instead of a <= b. That misses answers like 2 = 1² + 1².
- Trusting floating point sqrt for the perfect-square test without checking the integer result squared.
Frequently asked questions
Why is it safe to move a up when the sum is too small?
b only ever decreases, so every pair still to come with the current a has a b no larger than now. Those sums are all too small too, so this a can never be part of an answer.
Can a and b be the same number?
Yes. 2 = 1² + 1² and 8 = 2² + 2², which is why the loop runs while a <= b.
Is this related to Two Sum II?
It is the same idea. The sorted array is the list of squares 0, 1, 4, 9, ..., and the target is c.