Magicsheet logo

Perfect Squares

Medium
68.9%
Updated 6/1/2025

Perfect Squares

What is this problem about?

The Perfect Squares problem asks for the minimum number of perfect square numbers (1, 4, 9, 16, ...) that sum to a given number n. This coding problem is solved by BFS (treating each number as a node with edges to n-square² for all valid squares) or DP (coin change variant with coin denominations being perfect squares). The math, BFS, and dynamic programming interview pattern is the core.

Why is this asked in interviews?

Apple, Goldman Sachs, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it demonstrates two elegant approaches to the same problem: BFS for minimum steps and DP for minimum coins. It also connects to Lagrange's Four-Square Theorem (every positive integer is the sum of at most 4 perfect squares).

Algorithmic pattern used

DP (coin change). dp[i] = minimum squares summing to i. For each i: try all perfect squares j² ≤ i: dp[i] = min(dp[i], dp[i-j²]+1). Initialize dp[0]=0, all others=∞. Answer = dp[n].

BFS alternative: Each level represents one more square added. Start from n, BFS toward 0. Level = number of squares used.

Example explanation

n=12. Precompute squares ≤ 12: {1,4,9}. dp[0]=0. dp[1]=1 (1). dp[2]=2 (1+1). dp[3]=3 (1+1+1). dp[4]=1 (4). dp[5]=2 (4+1). ... dp[9]=1 (9). dp[10]=2 (9+1). dp[11]=3 (9+1+1). dp[12]=3 (4+4+4). Answer = 3.

Common mistakes candidates make

  • Not precomputing all perfect squares up to n.
  • Initializing dp[0]=1 instead of 0.
  • Using O(n√n) DP without considering BFS alternative.
  • Not knowing Lagrange's theorem (always ≤ 4, useful for bounding).

Interview preparation tip

Perfect Squares is both a BFS and DP problem — knowing both approaches demonstrates versatility. The DP is coin change with fixed denominations (perfect squares). The BFS gives minimum distance in an implicit graph. Lagrange's theorem provides an O(1) upper bound (answer is always 1, 2, 3, or 4). Knowing this theorem helps with sanity checking and early termination.

Similar Questions