Perfect Squares solution explained
Perfect Squares asks for the fewest perfect squares (1, 4, 9, 16 and so on) that add up to a given positive integer n. The standard answer is dynamic programming: best[v] is 1 plus the smallest best[v - k²] over every square k² up to v, which takes O(n · √n) time. A breadth-first search over remainders finds the same answer, and number theory shows it is never more than 4 and pins it down in O(√n).
By Evin JohnPublished 7 min read
The problem, restated
A tiler only stocks square tiles whose areas are perfect squares: 1, 4, 9, 16, 25 and up. A customer wants to cover an area of exactly n square units with as few tiles as possible, and ignores the shape. How few tiles are needed? Any square may be used any number of times.
| n | Fewest squares | One way |
|---|---|---|
| 25 | 1 | 25 |
| 18 | 2 | 9 + 9 |
| 50 | 2 | 25 + 25, or 49 + 1 |
| 6 | 3 | 4 + 1 + 1 |
| 7 | 4 | 4 + 1 + 1 + 1 |
| 28 | 4 | 25 + 1 + 1 + 1, or 16 + 4 + 4 + 4 |
Greedy fails quickly. Taking the largest square that fits first gives 16 for 18, leaving 2 = 1 + 1, so three squares, while 9 + 9 needs only two. The problem needs a method that considers every square for the first piece.
Why interviewers ask it
It checks whether you recognize the unbounded minimum-count pattern behind an unusual wrapper. It also has three genuinely different solutions, which gives the interviewer room to push: the DP is the expected answer, the breadth-first version shows you can see shortest-path structure, and the number theory is a bonus that few candidates know but many interviewers enjoy hearing about.
Follow-ups
- Return the squares, not just the count. Store which square improved best[v] and walk back from n.
- Many queries for different n. Build the table once up to the largest n and answer each query in O(1).
- Use cubes instead of squares. The DP and BFS still work; the four-square result does not apply.
- Why is the answer never above 4? Lagrange's four-square theorem says every positive integer is a sum of four squares (allowing zeros).
Brute force
Try every square k² up to n as the first piece and solve n - k² recursively, keeping the smallest result plus one. Without caching, the same remainders are solved over and over and the running time grows exponentially. Caching the result for each remainder gives exactly the table below.
Dynamic programming
Make a list best of length n + 1 where best[v] is the fewest squares summing to v. best[0] = 0. For each v from 1 to n, try every square that fits, and take 1 + best[v - k²] at its smallest. The squares can be precomputed once. Every v looks at about √v squares, so the total work is O(n · √n).
def num_squares(n):
squares = [k * k for k in range(1, int(n ** 0.5) + 2) if k * k <= n]
best = [0] + [n] * n # n ones always work, so n is a safe upper bound
for v in range(1, n + 1):
for sq in squares:
if sq > v:
break
if best[v - sq] + 1 < best[v]:
best[v] = best[v - sq] + 1
return best[n]function numSquares(n) {
const best = new Int32Array(n + 1).fill(n);
best[0] = 0;
for (let v = 1; v <= n; v++) {
for (let k = 1; k * k <= v; k++) {
const candidate = best[v - k * k] + 1;
if (candidate < best[v]) best[v] = candidate;
}
}
return best[n];
}Trace 18. best[9] is 1, so best[18] can be best[9] + 1 = 2 through the square 9. best[17] is 2 (16 + 1) and best[14] is 3 (9 + 4 + 1), so the squares 1 and 4 give 3 and 4, and 16 gives best[2] + 1 = 3. The minimum is 2.
Breadth-first search
Think of each remainder as a node, with an edge from r to r - k² for every square that fits. The fewest squares is the shortest path from n to 0, and in an unweighted graph breadth-first search finds that level by level. Level one holds every n - k²; if any is 0, the answer is 1. Mark remainders as seen so each is expanded only once. The worst case matches the DP, but because answers are at most 4 the search stops after very few levels.
def num_squares_bfs(n):
squares = [k * k for k in range(1, int(n ** 0.5) + 2) if k * k <= n]
level, frontier, seen = 0, {n}, {n}
while frontier:
level += 1
next_frontier = set()
for r in frontier:
for sq in squares:
if sq > r:
break
if sq == r:
return level
if r - sq not in seen:
seen.add(r - sq)
next_frontier.add(r - sq)
frontier = next_frontier
return levelThe number theory shortcut
Two classical results finish the job. Lagrange's four-square theorem says the answer is at most 4. Legendre's three-square theorem says a number needs all four exactly when it has the form 4^a · (8b + 7). So: return 1 if n is a perfect square; strip factors of 4 and return 4 if what remains leaves remainder 7 when divided by 8; return 2 if n equals some a² + b²; otherwise return 3. Only the two-square check needs a loop, up to √n.
from math import isqrt
def num_squares_math(n):
if isqrt(n) ** 2 == n:
return 1
m = n
while m % 4 == 0:
m //= 4
if m % 8 == 7:
return 4
for a in range(1, isqrt(n) + 1):
b2 = n - a * a
if isqrt(b2) ** 2 == b2:
return 2
return 3Present this as an extra, after the DP. Most interviewers want to see the general method, and stating two theorems without the DP can read as a memorized trick. If you mention it, say which theorem gives which step.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Plain recursion | Exponential | O(n) stack |
| Bottom-up table | O(n · √n) | O(n) |
| Breadth-first search over remainders | O(n · √n) worst case, usually far less | O(n) |
| Four-square and three-square theorems | O(√n) | O(1) |
Edge cases
- n = 1, 2 and 3: answers 1, 2 and 3, all from ones.
- A perfect square: 1.
- Numbers of the form 4^a · (8b + 7), such as 7, 15, 28 and 60: always 4.
- Large n in the table version, where O(n · √n) gets slow and the theorem version still answers instantly.
Common mistakes
- Taking the largest square first, which fails on 18.
- Initializing best with 0 instead of a large value, so every minimum stays 0.
- Building the list of squares with a loop bound that misses the largest square at or below n.
- Running breadth-first search without a seen set, which repeats the same remainders many times.
- Claiming the theorem answer without saying where the cases come from.
How to explain it out loud
Fictional example
- Candidate
- This is the fewest-coins problem where the coins are 1, 4, 9 and so on. Greedy fails: for 18 it takes 16 and needs two more ones, but 9 plus 9 is two.
- Candidate
- So best of v is one plus the minimum of best of v minus each square. Each value checks about root v squares, so the total is n root n.
- Candidate
- As a side note, the answer can never exceed 4 by Lagrange's theorem, and Legendre's theorem says exactly which numbers need 4. With those I can answer in root n, but the table is the general method.
Related problems
Coin Change II counts the combinations of coins instead of minimizing them, so it uses a sum where this page uses a minimum. Ugly Number II builds a sequence from a small set of factors. Sqrt(x) shows how to compute an integer square root without floating point, which is the check used in the theorem version.
Practicing with Natively
This problem rewards connecting it to fewest coins out loud before writing code. When you practice, Natively on Mac or Windows can read the problem from a screenshot and suggest the DP framing to check against your own, and the mock transcript shows whether you explained why greedy fails before the interviewer asked. More on the AI interview assistant.
Questions people ask
How do you solve the Perfect Squares problem?
Use a table where best[0] = 0 and best[v] = 1 + the minimum of best[v - k²] over every square k² up to v. The answer is best[n]. It is the fewest-coins problem with the squares as coins.
What is the time complexity of Perfect Squares?
The DP takes O(n · √n) time and O(n) memory, since each value tries about √v squares. The number theory version takes O(√n).
Why is the answer to Perfect Squares never more than 4?
Lagrange's four-square theorem states that every positive integer is a sum of four squares. Legendre's three-square theorem adds that exactly the numbers of the form 4^a · (8b + 7) need all four.
Can you solve Perfect Squares with BFS?
Yes. Treat each remainder as a node with edges to remainder minus each square. The fewest squares is the shortest path to 0, which breadth-first search finds level by level.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
