Perfect Squares
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #279
Return the least number of perfect squares (1, 4, 9, 16, …) that sum to n.
Examples
text
n = 12 → 3 (4 + 4 + 4)
n = 13 → 2 (4 + 9)Hints
- It's Coin Change where the coins are the squares ≤ n.
dp[i] = min over j*j ≤ i of dp[i − j*j] + 1.
Approach
DP: dp[0] = 0, and dp[i] = 1 + min(dp[i − s]) over squares s ≤ i. That's O(n√n).
Math shortcut (Lagrange's four-square theorem): every number is a sum of at most 4 squares. The answer is 4 exactly when n = 4^a(8b + 7) (Legendre's three-square theorem). Otherwise, check whether n is a square (answer 1) or a sum of two squares (2), and if not the answer is 3. That's O(√n). Mention it, but the DP is what interviewers usually expect.
Complexity
Time: O(n√n) for the DP (O(√n) for the math). Space: O(n) for the DP.
Python solution
def numSquares(n):
squares = [j * j for j in range(1, int(n ** 0.5) + 1)]
dp = [0] + [float('inf')] * n
for i in range(1, n + 1):
for s in squares:
if s > i:
break
if dp[i - s] + 1 < dp[i]:
dp[i] = dp[i - s] + 1
return dp[n]JavaScript solution
function numSquares(n) {
// Number theory: Lagrange (≤4), Legendre (=4 iff n = 4^a(8b+7)).
const isSq = (x) => { const r = Math.floor(Math.sqrt(x)); return r * r === x; };
if (isSq(n)) return 1;
let m = n;
while (m % 4 === 0) m /= 4;
if (m % 8 === 7) return 4;
for (let j = 1; j * j <= n; j++) if (isSq(n - j * j)) return 2;
return 3;
}