C++ 0279.cpp
class Solution {
static vector<int> minn;
void precompute()
{
const int limit = 10000;
const int invalid = 9999999;
minn.resize(limit+1, invalid);
int iteration = 1;
for (auto i = 1; i*i <= limit; i++)
minn[i*i] = 1;
int numFound = 9999999;
while (numFound > 0)
{
numFound = 0;
iteration++;
for (auto i = limit; i >= 1; i--)
if (minn[i] != invalid)
for (auto j = 1; i + j*j <= limit; j++)
if (minn[i + j*j] == invalid)
{
minn[i + j*j] = iteration;
numFound++;
}
}
}
public:
int numSquares(int n) {
if (minn.empty())
precompute();
return minn.at(n);
}
};
vector<int> Solution::minn;
Difficulty
and has an acceptance rate of about 57% (1+ million submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Dynamic Programming
- Math
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 presented implementation solves the classic “minimum number of perfect squares that sum to n” problem. It does so by building a table of answers for every integer up to a fixed bound (10 000) once, and then answering each query in constant time. The table is stored in a static vector<int> so that all instances of Solution share the same pre-computed data.
Precomputation Logic
The heart of the algorithm resides in precompute(). It first defines a numeric limit and a sentinel value that marks entries that have not yet been discovered.
const int limit = 10000;
const int invalid = 9999999;
minn.resize(limit+1, invalid);
The vector minn is sized to hold indices from 0 through limit. Every entry is initially set to invalid, guaranteeing that later checks can reliably distinguish between “unknown” and “known” values.
Next, the routine seeds the table with the trivial case: any perfect square requires exactly one term.
for (auto i = 1; i*i <= limit; i++)
minn[i*i] = 1;
At this point the table contains correct answers for all square numbers and still holds invalid for the rest.
The algorithm then expands outward from the known entries, layer by layer, using an iterative process that resembles breadth-first search on the implicit graph where an edge connects i to i + j*j. The variable iteration records the current distance (i.e., the number of squares used).
int iteration = 1;
int numFound = 9999999;
while (numFound > 0)
{
numFound = 0;
iteration++;
for (auto i = limit; i >= 1; i--)
if (minn[i] != invalid)
for (auto j = 1; i + j*j <= limit; j++)
if (minn[i + j*j] == invalid)
{
minn[i + j*j] = iteration;
numFound++;
}
}
The outer while loop continues until a full pass produces no new entries (numFound stays zero). Inside, the algorithm scans the table from the highest index down to 1. For each already-known entry i, it tries to add every square j*j that keeps the sum within the limit. If the target cell i + j*j is still marked invalid, it receives the current iteration value, indicating that the minimum number of squares for that sum is exactly iteration. The counter numFound records how many new cells were filled during the pass; when it becomes zero the table is complete.
Query Handling
The public method numSquares(int n) provides the answer for a specific n. It lazily triggers the precomputation on the first call.
int numSquares(int n) {
if (minn.empty())
precompute();
return minn.at(n);
}
The use of minn.at(n) performs bounds checking, so an out-of-range request will raise an exception rather than returning an undefined value. This defensive check ensures that callers receive a clear failure signal if they ask for a number larger than the supported limit.
Edge Cases Handled
The implementation explicitly guards against uninitialized table entries by initializing every slot with the sentinel invalid. Consequently, any attempt to read a value before it has been discovered will never mistakenly return a plausible answer.
The lazy initialization pattern (if (minn.empty()) precompute();) guarantees that the heavy precomputation work is performed only once, even if many Solution objects are created.
The final lookup uses vector::at, which throws std::out_of_range if n is negative or exceeds limit. This built-in check protects the routine from invalid inputs without requiring additional manual validation code.
Because the algorithm starts the expansion from all perfect squares, the case where n itself is a perfect square is resolved immediately with the value 1.
Performance Optimizations
A key optimization is the static storage of the answer table. By declaring minn as a static member, the program allocates the table only once for the entire process, eliminating repeated allocation and recomputation across multiple queries.
The precomputation loop iterates from the highest index downwards. This direction ensures that newly discovered values in the current iteration are not immediately used to generate further values within the same pass, preserving the layer-by-layer nature of the search and preventing redundant updates.
The inner loop stops as soon as i + j*j exceeds the limit, avoiding unnecessary iterations beyond the pre-defined bound.
The sentinel invalid serves a dual purpose: it marks undiscovered entries and also acts as a cheap boolean flag, allowing the algorithm to skip already solved positions without extra data structures.
Finally, the termination condition (numFound > 0) means the outer loop runs only as many times as there are distinct distance layers needed to cover the entire range. Once every entry has been assigned a minimum count, the loop exits immediately, preventing any superfluous passes.
ELI5 - Simplified Explanation
Imagine a giant box filled with empty cubbyholes, numbered from one all the way up to ten thousand. The goal is to figure out the smallest number of square tiles needed to perfectly fill each cubbyhole. A square tile could be a tiny one by one, a four by four, a nine by nine, or any other size where the sides are the same length.
The code starts by checking if the cubbyholes are already filled. If they are empty, it runs a special task to solve the puzzle for every single one. It first places single square tiles into holes like one, four, nine, and sixteen, because those are perfect squares and only need one tile.
Next, the computer plays a game where it tries to combine the squares already in the holes with even more square tiles. It looks at every hole that already has a number of tiles, picks a new square size, and checks if adding that new square to the hole creates a total value that is still under the limit. If it finds a hole that does not have a solution yet, it marks it with the current number of steps taken. It repeats this over and over, slowly filling in every single cubbyhole until every number has the smallest possible count of square tiles assigned to it. Once this giant map is finished, finding the answer for any specific number is as quick as looking up a name in a book.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| 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 | ||||||||||
| aylei | Rust | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 264: Ugly Number II
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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