Problem
Given a non-negative integerc, decide whether there’re two integers a and b such that a^2 + b^2 = c.
Examples
Constraints
- 0 <= c <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 633 with 21 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 633 # by problem number
lcpy gen -s sum_of_square_numbers # by problem name
c, decide whether there’re two integers a and b such that a^2 + b^2 = c.
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Input: c = 3
Output: false
from math import isqrt
class Solution:
# Time: O(sqrt(c))
# Space: O(1)
def judge_square_sum(self, c: int) -> bool:
left, right = 0, isqrt(c)
while left <= right:
total = left * left + right * right
if total == c:
return True
if total < c:
left += 1
else:
right -= 1
return False
| Time | Space |
|---|---|
| O(sqrt(c)) | O(1) |