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
Difficulty
and has an acceptance rate of about 37% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Search
- Math
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 367: Valid Perfect Square
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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