Sum of Square Numbers — LeetCode 633 Python Solution

MediumMathTwo PointersBinary Search
Problem
#633
Reading time
2 min

The problem

Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

Example

Input
c = 5
Output
true
Explanation
1 * 1 + 2 * 2 = 5

Python solution

Python
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

MeasureComplexity
TimeO(\sqrt{c}), where c is the given non-negative integer
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 633. Sum of Square Numbers is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 633. Sum of Square Numbers?
LeetCode 633. Sum of Square Numbers is rated Medium on LeetCode.
What is the time complexity of LeetCode 633. Sum of Square Numbers?
The Python solution on this page runs in O(\sqrt{c}), where c is the given non-negative integer.
What is the space complexity of LeetCode 633. Sum of Square Numbers?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 633. Sum of Square Numbers cover?
LeetCode 633. Sum of Square Numbers is tagged Math, Two Pointers and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview