Perfect Squares
Perfect Squares is a medium dynamic programming problem solved with the knapsack pattern.
The best approach, optimal (four-square theorem), runs in O(√n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every last square) up.
Problem
A perfect square is a number you get by multiplying a whole number by itself: 1, 4, 9, 16, 25 and so on.
Given a positive integer n, return the smallest number of perfect squares that add up to exactly n. You may use the same square as many times as you like.
For example, 12 can be written as 9 + 1 + 1 + 1 (four squares) or as 4 + 4 + 4 (three squares), so the answer for 12 is 3.
Examples
Example 1
- Input
n = 12- Output
3- Why
- 12 = 4 + 4 + 4. No two squares add up to 12: 12 - 1 = 11, 12 - 4 = 8 and 12 - 9 = 3 are not squares. The greedy start 9 + 1 + 1 + 1 needs four.
Example 2
- Input
n = 13- Output
2- Why
- 13 = 4 + 9, and 13 itself is not a square.
Example 3
- Input
n = 7- Output
4- Why
- 7 = 4 + 1 + 1 + 1. The only squares below 7 are 1 and 4, and no choice of three of them reaches 7.
Constraints
1 <= n <= 10^4
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every last square) | Exponential | O(n) |
| Bottom-up DP (squares as coins) | O(n √n) | O(n) |
| Optimal (four-square theorem) | O(√n) | O(1) |
1Brute force (try every last square)
ExponentialEach call branches into up to √n calls, and the same remainders are solved many times. Already n = 40 needs almost two million calls.O(n)The deepest chain subtracts 1 each time, so the recursion stack can be n calls deep.Any sum of squares that makes n ends with some square k * k. Remove it, and the rest makes n - k * k. So the fewest squares for n is 1 plus the fewest for n - k * k, for the best k. Plain recursion tries every k at every level and solves the same smaller numbers again and again.
- If n is 0, no squares are needed: return 0.
- Start with best = n, since n ones always work.
- For every k with k * k <= n, recurse on n - k * k and keep best = min(best, 1 + that answer).
- Return best.
class Solution {
public int numSquares(int n) {
if (n == 0) return 0;
int best = n; // n ones always work
for (int k = 1; k * k <= n; k++)
best = Math.min(best, 1 + numSquares(n - k * k));
return best;
}
}class Solution:
def numSquares(self, n: int) -> int:
if n == 0:
return 0
best = n # n ones always work
k = 1
while k * k <= n:
best = min(best, 1 + self.numSquares(n - k * k))
k += 1
return bestclass Solution {
public:
int numSquares(int n) {
if (n == 0) return 0;
int best = n; // n ones always work
for (int k = 1; k * k <= n; k++)
best = min(best, 1 + numSquares(n - k * k));
return best;
}
};function numSquares(n) {
if (n === 0) return 0;
let best = n; // n ones always work
for (let k = 1; k * k <= n; k++)
best = Math.min(best, 1 + numSquares(n - k * k));
return best;
}2Bottom-up DP (squares as coins)
O(n √n)Each of the n entries tries at most √n squares.O(n)The dp array has n + 1 entries.There are only n + 1 different questions: the fewest squares for 0, 1, ..., n. Answer them in increasing order and store them in an array, so each one is computed once. dp[i] is 1 plus the smallest dp[i - k * k] over the squares that fit. This is the unbounded knapsack pattern, the same as making change with coins 1, 4, 9, 16 and so on, each usable any number of times.
- Make an array dp of size n + 1 with dp[0] = 0.
- For i from 1 to n: start with dp[i] = i (all ones).
- For every k with k * k <= i, set dp[i] = min(dp[i], dp[i - k * k] + 1).
- Return dp[n].
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = i; // i ones
for (int k = 1; k * k <= i; k++)
dp[i] = Math.min(dp[i], dp[i - k * k] + 1);
}
return dp[n];
}
}class Solution:
def numSquares(self, n: int) -> int:
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = i # i ones
k = 1
while k * k <= i:
dp[i] = min(dp[i], dp[i - k * k] + 1)
k += 1
return dp[n]class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, 0);
for (int i = 1; i <= n; i++) {
dp[i] = i; // i ones
for (int k = 1; k * k <= i; k++)
dp[i] = min(dp[i], dp[i - k * k] + 1);
}
return dp[n];
}
};function numSquares(n) {
const dp = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
dp[i] = i; // i ones
for (let k = 1; k * k <= i; k++)
dp[i] = Math.min(dp[i], dp[i - k * k] + 1);
}
return dp[n];
}3Optimal (four-square theorem)
O(√n)The two-squares test tries at most √n values of a, each with a constant-time square check. Stripping factors of 4 takes O(log n).O(1)Only a few integers.Number theory settles this problem. The four-square theorem says every positive integer is a sum of at most four squares. The three-square theorem says a number needs all four exactly when it has the form 4^a × (8b + 7): strip every factor of 4 and look at the remainder mod 8. So the answer is 4 for those numbers, 1 if n is a square, 2 if n - a * a is a square for some a, and 3 otherwise.
- If n is a perfect square, return 1.
- For every a with a * a <= n, if n - a * a is a perfect square, return 2.
- Divide a copy of n by 4 while it is divisible by 4. If the result leaves remainder 7 when divided by 8, return 4.
- Otherwise return 3.
class Solution {
public int numSquares(int n) {
if (isSquare(n)) return 1;
for (int a = 1; a * a <= n; a++)
if (isSquare(n - a * a)) return 2;
int m = n;
while (m % 4 == 0) m /= 4;
if (m % 8 == 7) return 4;
return 3;
}
private boolean isSquare(int x) {
int r = (int) Math.sqrt(x);
return r * r == x;
}
}class Solution:
def numSquares(self, n: int) -> int:
def is_square(x: int) -> bool:
r = math.isqrt(x)
return r * r == x
if is_square(n):
return 1
a = 1
while a * a <= n:
if is_square(n - a * a):
return 2
a += 1
m = n
while m % 4 == 0:
m //= 4
if m % 8 == 7:
return 4
return 3class Solution {
public:
int numSquares(int n) {
if (isSquare(n)) return 1;
for (int a = 1; a * a <= n; a++)
if (isSquare(n - a * a)) return 2;
int m = n;
while (m % 4 == 0) m /= 4;
if (m % 8 == 7) return 4;
return 3;
}
private:
bool isSquare(int x) {
int r = (int) sqrt((double) x);
return r * r == x;
}
};function numSquares(n) {
const isSquare = (x) => {
const r = Math.floor(Math.sqrt(x));
return r * r === x;
};
if (isSquare(n)) return 1;
for (let a = 1; a * a <= n; a++)
if (isSquare(n - a * a)) return 2;
let m = n;
while (m % 4 === 0) m /= 4;
if (m % 8 === 7) return 4;
return 3;
}Edge cases to test
- n = 1: a single square (answer 1)
- n is itself a perfect square, such as 4, 9 or 10000 (answer 1)
- n is a sum of two squares, such as 2, 5 or 13 (answer 2)
- Numbers of the form 4^a × (8b + 7), such as 7, 15, 28 or 9999, always need exactly 4
- Greedy traps: always taking the largest square that fits is wrong. For 12 it takes 9 first and ends with four squares instead of three
- The answer is never more than 4, for any n
Hints
Hint 1
Think about the last square in an optimal sum. If it is k * k, what is left is n - k * k, and the rest must be an optimal sum for that smaller number.
Hint 2
So the answer for n is 1 plus the smallest answer for n - k * k, over every k with k * k <= n. This is the same shape as making change with coins, where the coins are 1, 4, 9, 16, ...
Hint 3
Fill an array dp from 0 up to n, with dp[0] = 0. Each entry only reads smaller entries.
Hint 4
A classic theorem says every positive integer is a sum of at most four squares, and exactly the numbers 4^a × (8b + 7) need all four. That leaves only 1, 2 or 3 to tell apart.
FAQ
What is the best time complexity for Perfect Squares?
Optimal (four-square theorem) runs in O(√n) time and O(1) extra space. The two-squares test tries at most √n values of a, each with a constant-time square check. Stripping factors of 4 takes O(log n).
Which pattern does Perfect Squares use?
It is a dynamic programming problem that uses the knapsack pattern. Other problems with the same pattern: 0 - 1 Knapsack Problem, Fractional Knapsack, Knapsack with Duplicate Items.
Is there a brute force solution for Perfect Squares?
Yes. Brute force (try every last square) takes Exponential time and O(n) space. Any sum of squares that makes n ends with some square k k.
Which edge cases should I test for Perfect Squares?
n = 1: a single square (answer 1); n is itself a perfect square, such as 4, 9 or 10000 (answer 1); n is a sum of two squares, such as 2, 5 or 13 (answer 2); Numbers of the form 4^a × (8b + 7), such as 7, 15, 28 or 9999, always need exactly 4; Greedy traps: always taking the largest square that fits is wrong. For 12 it takes 9 first and ends with four squares instead of three; The answer is never more than 4, for any n.