Perfect Squares

MediumDynamic Programming · Unbounded Knapsack · Math🧩 Knapsack DPLeetCode #279 ↗Updated

Problem

Given a positive integer n, return the fewest perfect squares (1, 4, 9, 16, …) that add up to exactly n. The same square may be used any number of times.
Inputn = 12Output3 (4 + 4 + 4)
Inputn = 13Output2 (4 + 9)

1 ≤ n ≤ 104

Try it yourself

Java
class Solution {
    public int numSquares(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
It is coin change with coins 1, 4, 9, …: best(n) = 1 + min best(n - k²). Number theory then caps the answer at 4 (Lagrange), and tells exactly when it is 1, 2, 3 or 4 — no table needed.
PatternKnapsack DP

Instinct Choose items to hit or stay under a target sum (can it be done, best value, fewest items, how many ways) - index a DP array by the remaining capacity.

Memory hack Once? Walk back. Many? Walk forward. Each item used at most once loops capacity downward; reusable items loop it upward.

Open the Knapsack DP guide →

Approaches

Brute ForcePlain Recursion over the Last Square

Time O(√nn) worst caseSpace O(n)

Pick which square k² to use first, solve the remainder n - k² recursively, and keep the minimum. It explores every way of writing n as a sum of squares, recomputing the same remainders many times.

Java
public int numSquares(int n) {
    if (n == 0) return 0;
    int best = Integer.MAX_VALUE;
    for (int k = 1; k * k <= n; k++) {
        best = Math.min(best, 1 + numSquares(n - k * k));
    }
    return best;
}

Correct, but exponential — hopeless well before n = 104.

At a glance

LevelApproachTimeSpace
Brute ForcePlain Recursion over the Last SquareO(√nn) worst caseO(n)
BetterBottom-Up DP (Unbounded Knapsack)O(n √n)O(n)
OptimalNumber Theory (Four-Square Theorem)O(√n)O(1)
Common pitfalls
  • Greedily taking the largest square: 12 = 9+1+1+1 (4) but 4+4+4 is 3.
  • Initialising dp[i] to 0 instead of a large value (or i).
  • Using floating sqrt without checking r*r == x exactly.
Interview tips
  • Say “this is coin change where coins are squares” to frame the DP instantly.
  • BFS from n by subtracting squares also works and stops at the first level reached.
  • If you mention Lagrange, be ready to explain the 4a(8b+7) rule.
Pattern
Unbounded knapsack (min count) → fewest reusable items that sum to a target.
My notes saved in this browser