Problem 633

Abstract / Summary

Check if a given number can be written as the sum of one or more squares of integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0633.py

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        all = set()

        i = 0
        while i*i <= c:
            if c == i*i:
                return True

            all.add(i*i)
            i += 1

        for squares in all:
            if (c - squares) in all:
                return True

        return False
17 lines | 352 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search
  • Math
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method judgeSquareSum that determines whether a given non-negative integer c can be expressed as the sum of two perfect squares. The algorithm proceeds in two phases: first it enumerates all square numbers that do not exceed c, storing them in a set for constant-time lookup; second it checks whether any pair of stored squares adds up to c. The method returns True as soon as a valid representation is found, otherwise it returns False.

Core Logic

Generating Square Numbers

The method begins by creating an empty set named all. It then iterates with a variable i starting at zero, incrementing i while the square i*i remains less than or equal to c. During each iteration the square is added to the set. A direct equality test is performed to catch the trivial case where c itself is a perfect square.

all = set()

i = 0
while i*i <= c:
    if c == i*i:
        return True

    all.add(i*i)
    i += 1

Searching for a Complementary Square

After the set is populated, the method iterates over each stored square value, referred to as squares. For each value it computes the difference c - squares and checks whether this difference also exists in the set. If such a complementary square is found, the method immediately returns True.

for squares in all:
    if (c - squares) in all:
        return True

Final Result

If the loop completes without finding a matching pair, the method concludes that c cannot be expressed as the sum of two squares and returns False.

return False

Edge Cases Handled

The algorithm explicitly handles the situation where c is zero. Since the loop condition i*i <= c is satisfied for i = 0, the square 0 is added to the set, and the subsequent complement check finds that 0 - 0 is also present, resulting in a True return.

Another edge case is when c itself is a perfect square. The early equality test inside the generation loop detects this condition and returns True without further processing.

The use of a set ensures that duplicate squares are automatically eliminated, which is relevant when c is small and the range of i values is limited.

Performance Optimizations

Storing the squares in a hash-based set provides constant-time membership checks during the complement search. This eliminates the need for nested loops that would otherwise compare each pair of squares directly, reducing the number of comparisons dramatically.

The early return when c equals i*i avoids unnecessary work for inputs that are perfect squares, allowing the method to finish in linear time relative to the square root of c for those cases.

By iterating only up to the integer square root of c (while i*i <= c), the algorithm limits the size of the set to the minimal necessary collection of candidate squares, preventing excess memory usage.

The two-phase approach-first building the set, then performing lookups-leverages the fast average-case performance characteristics of Python’s built-in set type, resulting in an efficient overall solution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a box where you want to put two square blocks together to make a bigger pile of blocks that matches the number c. The first part of this code looks at every number and multiplies it by itself to see if it makes a square shape. It puts all these square shapes into a collection so they are easy to find later.

Once all those squares are safely in the collection, the code starts looking through them. It picks one square and checks if the leftover amount needed to reach the target number c is also a square that exists in the collection. If it finds two squares that fit perfectly together to make the total, that means the math works out just right.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.30 | σ = 1.30

Complexity Analysis

Time: sublinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
zfang399 C++
38 links | 23 authors | 8 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality