Perfect Squares
Medium
Topics
Return the fewest perfect squares that add up to n. A perfect square is an integer times itself: 1, 4, 9, 16 and so on.
Squares may be repeated.
Example 1
Input: n = 12 Output: 3 Explanation: 4 + 4 + 4. Using 9 instead leaves 3, which needs three 1s for four terms in total.
Example 2
Input: n = 13 Output: 2 Explanation: 4 + 9.
Example 3
Input: n = 1 Output: 1 Explanation: 1 is itself a perfect square.
Constraints
- 1 <= n <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Taking the largest square that fits and repeating is the obvious idea and it is wrong. For n = 12 it picks 9, then 1, 1, 1 — four terms, when three 4s do it. Nothing about this problem rewards being locally frugal.
What does work is to build up the answer for every total from 1 to n. The fewest squares for a total t is one more than the fewest for t minus some square, taken over every square that fits. Each smaller total is already settled when t is reached, so each is computed once.
An equivalent view is a walk outward from n, where a step subtracts a square and every step costs the same. The first time zero is reached, it is reached in the fewest steps, and in practice that touches far fewer totals than filling the whole table.
There is also a closed-form answer. Lagrange proved every positive integer is the sum of at most four squares, and a classical result says the answer is 4 exactly when n has the form 4^k * (8m + 7); it is 1 when n is a square and 2 when n is a sum of two squares. That gives a constant-time test, though it is number theory rather than anything the problem teaches.
Approach
- Let
fewest[t]be the answer for totalt, withfewest[0] = 0. - For each total
tfrom1ton, consider every squarej * jthat is at mostt. - Set
fewest[t]to the smallestfewest[t - j * j] + 1over those squares. - Return
fewest[n]. - The outward-walk variant: explore from
n, at each step subtracting any square that fits, and return the number of steps when zero is first reached.
Walkthrough
n = 12
fewest[0] = 0
fewest[1] = fewest[0] + 1 = 1 using 1
fewest[2] = fewest[1] + 1 = 2 1 + 1
fewest[3] = fewest[2] + 1 = 3 1 + 1 + 1
fewest[4] = min(fewest[3]+1, fewest[0]+1) = 1 using 4
fewest[5] = min(fewest[4]+1, fewest[1]+1) = 2 4 + 1
fewest[6] = 3
fewest[7] = 4
fewest[8] = min(fewest[7]+1, fewest[4]+1) = 2 4 + 4
fewest[9] = min(..., fewest[0]+1) = 1 using 9
fewest[10] = 2 9 + 1
fewest[11] = 3
fewest[12] = min(fewest[11]+1, using 1 -> 4
fewest[8]+1, using 4 -> 3
fewest[3]+1) = 3 using 9 -> 4
answer 3, as 4 + 4 + 4
why taking the largest square first fails
12 -> take 9, leaves 3
-> 3 needs 1 + 1 + 1
-> total 4 terms
but 4 + 4 + 4 is 3 terms. The big square was a trap.Complexity
- Time — O(n * sqrt(n)): each of the n totals tries every square up to it, and there are sqrt(total) of those.
- Space — O(n): one entry per total.
Common Pitfalls
- Taking the largest square that fits and recursing. It gives 4 for
n = 12instead of 3. - Initialising the table to zero rather than to a large value, so every total reports 0.
- Looping squares as
j <= totalinstead ofj * j <= total, which is correct but doesnwork per total rather thansqrt(n). - Forgetting
fewest[0] = 0, which is what lets an exact square answer 1. - Reaching for the four-squares theorem without the
4^kfactor in the test, which misclassifies values such as 28.
Full Solution — all languages
class Solution:
def numSquares(self, n):
fewest = [0] * (n + 1)
for total in range(1, n + 1):
best = total # worst case: that many 1s
j = 1
while j * j <= total:
best = min(best, fewest[total - j * j] + 1)
j += 1
fewest[total] = best
return fewest[n]import java.util.*;
class Solution {
public int numSquares(int n) {
int[] fewest = new int[n + 1];
for (int total = 1; total <= n; total++) {
int best = total;
for (int j = 1; j * j <= total; j++) {
best = Math.min(best, fewest[total - j * j] + 1);
}
fewest[total] = best;
}
return fewest[n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numSquares(int n) {
vector<int> fewest(n + 1, 0);
for (int total = 1; total <= n; total++) {
int best = total;
for (int j = 1; j * j <= total; j++) {
best = min(best, fewest[total - j * j] + 1);
}
fewest[total] = best;
}
return fewest[n];
}
};/**
* @param {number} n
* @return {number}
*/ var numSquares = function(n) {
const fewest = new Array(n + 1).fill(0);
for (let total = 1; total <= n; total++) {
let best = total;
for (let j = 1; j * j <= total; j++) {
best = Math.min(best, fewest[total - j * j] + 1);
}
fewest[total] = best;
}
return fewest[n];
};