#633
Sum of Square Numbers
MediumMathTwo PointersBinary SearchTwo PointersMathematical Properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a two-pointer technique, leveraging the fact that both a and b can be derived from the square root of c. This reduces the number of checks significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers, a at 0 and b at the integer square root of c.
- 2Step 2: While a is less than or equal to b, calculate the sum of squares: sum = a² + b².
- 3Step 3: If sum equals c, return true. If sum is less than c, increment a. If sum is greater than c, decrement b.
solution.py13 lines
1import math
2
3def judgeSquareSum(c):
4 a, b = 0, int(math.sqrt(c))
5 while a <= b:
6 sum_squares = a * a + b * b
7 if sum_squares == c:
8 return True
9 elif sum_squares < c:
10 a += 1
11 else:
12 b -= 1
13 return Falseℹ
Complexity note: The time complexity is O(n) because we only iterate through the values of a and b once, adjusting them based on the sum of their squares.
- 1The sum of two squares can be efficiently checked using mathematical properties and two-pointer technique.
- 2Understanding the relationship between squares and their roots helps optimize the search.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.