Perfect Squares (LeetCode 279): Solution and Explanation
Find the fewest perfect squares (1, 4, 9, 16, ...) that add up to n. It is a coin-change problem where the coins are the squares up to n.
Intuition
Greedy looks tempting but fails. For n = 12, taking the largest square first gives 9 + 1 + 1 + 1, four squares, while 4 + 4 + 4 needs only three.
Instead, think about the last square in an optimal sum. If it is j*j, the rest of the sum is an optimal split of i - j*j. You do not know which j is right, so try all of them and keep the smallest.
That gives dp[i] = min over j*j <= i of dp[i - j*j] + 1, where dp[0] = 0 because zero needs no squares. Every dp[i - j*j] is smaller than i, so filling dp from 1 upward means each lookup is already final.
The answer is never more than 4 (Lagrange's four-square theorem), but the DP does not need that fact.
Approach: Bottom-up DP over amounts
- Create dp of size n + 1 with dp[0] = 0 and every other entry infinity.
- For each i from 1 to n, loop j = 1, 2, ... while j*j <= i.
- Set dp[i] = min(dp[i], dp[i - j*j] + 1).
- Return dp[n].
Step-by-step example
n = 12
- dp[0] = 0. dp[1..3] can only use 1, so they are 1, 2, 3.
- dp[4]: 4 - 4 = 0 gives dp[0] + 1 = 1, better than dp[3] + 1 = 4. dp[5..7] = 2, 3, 4.
- dp[8]: 8 - 4 = 4 gives dp[4] + 1 = 2. dp[9] = 1 using 9 itself. dp[10] = dp[9] + 1 = 2, dp[11] = dp[2] + 1 = 3.
- dp[12]: 12 - 9 = 3 gives dp[3] + 1 = 4, 12 - 4 = 8 gives dp[8] + 1 = 3, 12 - 1 = 11 gives dp[11] + 1 = 4.
- The minimum is 3, so the answer is 3 (12 = 4 + 4 + 4).
Code: Python, Java, C++
1class Solution:
2 def numSquares(self, n: int) -> int:
3 dp = [0] + [float('inf')] * n
4 for i in range(1, n + 1):
5 j = 1
6 while j * j <= i:
7 dp[i] = min(dp[i], dp[i - j * j] + 1)
8 j += 1
9 return dp[n]1class Solution {
2 public int numSquares(int n) {
3 int[] dp = new int[n + 1];
4 Arrays.fill(dp, Integer.MAX_VALUE);
5 dp[0] = 0;
6 for (int i = 1; i <= n; i++) {
7 for (int j = 1; j * j <= i; j++) {
8 dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
9 }
10 }
11 return dp[n];
12 }
13}1class Solution {
2public:
3 int numSquares(int n) {
4 vector<int> dp(n + 1, INT_MAX);
5 dp[0] = 0;
6 for (int i = 1; i <= n; i++) {
7 for (int j = 1; j * j <= i; j++) {
8 dp[i] = min(dp[i], dp[i - j * j] + 1);
9 }
10 }
11 return dp[n];
12 }
13};Time and space complexity
O(n * sqrt(n))
Each of the n entries checks every square up to it, about sqrt(i) of them.
O(n)
One dp array of n + 1 integers.
Other approaches
BFS over remainders (time O(n * sqrt(n)), space O(n))
Start from n and at each level subtract every square that fits. The first level that reaches 0 is the answer. It stops early when the answer is small, which it always is, but still visits many remainders.
Number theory (time O(sqrt(n)), space O(1))
Return 1 if n is a square, 4 if n has the form 4^a(8b + 7) (Legendre's three-square theorem), 2 if n = a*a + b*b for some a, and 3 otherwise. It is the fastest but relies on theorems an interviewer may not expect.
Common mistakes
- Using greedy (largest square first), which gives 4 instead of 3 for n = 12.
- Starting dp[0] at infinity instead of 0, which makes every perfect square look unreachable.
- Looping j with j < sqrt(i) using floating point and missing the exact square j*j == i.
- Recursing without memoization, which revisits the same remainders exponentially often.
Frequently asked questions
Why does greedy not work?
Taking the largest square can leave a remainder that is expensive to split. For 12, taking 9 leaves 3, which needs three 1s, while three 4s finish in three squares.
How is this related to Coin Change?
It is the same recurrence with the coins fixed to the squares 1, 4, 9, ... up to n, and every amount is reachable because 1 is a square.
Can the answer be larger than 4?
No. Lagrange's four-square theorem says every positive integer is a sum of at most four squares, so the result is always 1, 2, 3 or 4.