Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Perfect Squares
Problem
Given a positive integer n, find the smallest number of perfect squares (1, 4, 9, 16, ...) that add up to exactly n. The same square may be used more than once.
nis a positive integer up to around ten thousand.
Examples
n = 21→3, using16 + 4 + 1. Note that9 + 9 + 1 + 1 + 1uses five squares and is worse.n = 18→2, using9 + 9.n = 4→1. Four is itself a perfect square.
Hints
- If you knew the answer for every smaller number, how would you build the answer for
nfrom one of them plus a single square? - The "coins" here are the squares up to
n. There are only aboutsqrt(n)of them. - Unbounded knapsack with minimization:
fewest[i] = 1 + min(fewest[i - k*k] for k*k <= i). Equivalently, BFS fromnwhere each edge subtracts a square.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.