Problem 279

Abstract / Summary

Find the least number of perfect square numbers that add up to a given positive integer.

Note

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

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;
41 lines | 967 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Breadth First Search
  • Dynamic Programming
  • Math
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

Complexity Analysis

not analyzed yet

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++ 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++
51 links | 36 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Perfect Squares | Why not Greedy | Recursion | Memo | Leetcode 279'
codestorywithMIK 18 mins
Perfect Squares | Why not Greedy | Recursion | Memo | Leetcode 279
YouTube video 'LeetCode 279. Perfect Squares Explanation and Solution'
happygirlzt 6 mins
LeetCode 279. Perfect Squares Explanation and Solution
YouTube video 'Perfect Squares | LeetCode 279 | C++, Java, Python'
Knowledge Center 19 mins
Perfect Squares | LeetCode 279 | C++, Java, Python
YouTube video '279. Perfect Squares | 5 Ways | DP | Math | BFS | Lagrange & Legendre Theorem | Top-Down | Bottom Up'
Aryan Mittal 30 mins
279. Perfect Squares | 5 Ways | DP | Math | BFS | Lagrange & Legendre Theorem | Top-Down | Bottom Up
YouTube video 'Perfect Squares | Bottom UP | Made Easy | Google | Leetcode 279'
codestorywithMIK 12 mins
Perfect Squares | Bottom UP | Made Easy | Google | Leetcode 279
YouTube video '[Java] Leetcode 279. Perfect Squares [DP Integer Partition #2]'
Eric Programming 12 mins
[Java] Leetcode 279. Perfect Squares [DP Integer Partition #2]
YouTube video 'Leetcode 279: Perfect Squares'
Algorithms Casts 45 mins
Leetcode 279: Perfect Squares
YouTube video 'Perfect Squares | Leetcode 279 | Live coding session 🔥🔥🔥'
Coding Decoded 12 mins
Perfect Squares | Leetcode 279 | Live coding session 🔥🔥🔥
YouTube video 'Daily Leetcode #966: Nov 22, 2022 - 279. Perfect Squares'
Programming Live with Larry 10 mins
Daily Leetcode #966: Nov 22, 2022 - 279. Perfect Squares
YouTube video 'Leetcode | 279. Perfect Squares | Medium | Java Solutions [2 Methods - Top Down & Bottom Up DP]'
Developer Docs 16 mins
Leetcode | 279. Perfect Squares | Medium | Java Solutions [2 Methods - Top Down & Bottom Up DP]
YouTube video 'Perfect Squares | Day 27 | [ June LeetCoding Challenge ] [ Leetcode #279 ] [ 2020 ]'
Algorithms Made Easy 5 mins
Perfect Squares | Day 27 | [ June LeetCoding Challenge ] [ Leetcode #279 ] [ 2020 ]
YouTube video 'Perfect Squares || Leetcode 279 || leetcode medium || interview problem || c++ solution'
code Explainer 6 mins
Perfect Squares || Leetcode 279 || leetcode medium || interview problem || c++ solution
YouTube video '279. Perfect Squares | JavaScript | Recursion | Memoization | LeetCode Daily Challenge'
LeetCodeWithMonu 13 mins
279. Perfect Squares | JavaScript | Recursion | Memoization | LeetCode Daily Challenge
YouTube video 'Leetcode 279: Perfect Squares | Love Babbar DP Series'
ThinkCode 18 mins
Leetcode 279: Perfect Squares | Love Babbar DP Series
YouTube video 'Daily Leetcode #88: Jun 27, 2020 - 279. Perfect Squares'
Programming Live with Larry 10 mins
Daily Leetcode #88: Jun 27, 2020 - 279. Perfect Squares
YouTube video '279 || Perfect Squares || Leetcode Daily Challenge'
CodeFreaks 19 mins
279 || Perfect Squares || Leetcode Daily Challenge
YouTube video '279. Perfect Squares | February | Java | C++'
Mayur Programming Club 30 mins
279. Perfect Squares | February | Java | C++
YouTube video 'Leetcode 279  Perfect Squares (Really Struggled With This One)'
Luc Taylor 13 mins
Leetcode 279 Perfect Squares (Really Struggled With This One)
YouTube video '279. Perfect Squares | Leetcode | cpp | java'
Komal Pal 19 mins
279. Perfect Squares | Leetcode | cpp | java
YouTube video 'Daily Leetcode #562: Oct 14, 2021 - 279. Perfect Squares'
Programming Live with Larry 17 mins
Daily Leetcode #562: Oct 14, 2021 - 279. Perfect Squares
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 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