Imagine you're a mathematician trying to express any positive integer using the fewest possible perfect squares. A perfect square is a number that can be expressed as the product of an integer with itself - like 1 = 1×1, 4 = 2×2, 9 = 3×3, and 16 = 4×4.

Your challenge is to find the minimum number of perfect squares that sum up to a given integer n. For example, 12 can be expressed as 4 + 4 + 4 (three perfect squares) or as 4 + 8, but since 8 isn't a perfect square, we need 4 + 4 + 4. However, we can also express it as 9 + 1 + 1 + 1 (four squares), so the optimal answer is 3.

This problem tests your ability to find optimal decompositions and can be solved using dynamic programming, BFS, or mathematical insights about number theory.

Input & Output

example_1.py — Small Perfect Square
$ Input: n = 12
Output: 3
💡 Note: 12 = 4 + 4 + 4 (three perfect squares). We could also use 9 + 1 + 1 + 1 (four squares), but 3 is the minimum.
example_2.py — Already Perfect Square
$ Input: n = 13
Output: 2
💡 Note: 13 = 4 + 9 (two perfect squares). This is optimal since 13 itself is not a perfect square.
example_3.py — Edge Case
$ Input: n = 1
Output: 1
💡 Note: 1 is itself a perfect square (1²), so we only need one perfect square.

Visualization

Tap to expand
Perfect Squares Decomposition (n=12)Option 1: 9 + 1 + 1 + 1 = 12 (4 squares)91111= 4 squares ❌Option 2: 4 + 4 + 4 = 12 (3 squares) ✓444= 3 squares ✓Algorithm ComparisonBrute Force: Try all combinations• Time: Exponential O(n^√n)• Space: O(√n) recursion stackDynamic Programming: Build up solutions• Time: O(n√n)• Space: O(n) for DP tableBFS: Shortest path approachPerfect Squares ≤ 12: 1, 4, 9
Understanding the Visualization
1
Identify Available Squares
For n=12, we have squares: 1, 4, 9 (since 16 > 12)
2
Try All Combinations
12 = 9+1+1+1 (4 squares) or 12 = 4+4+4 (3 squares)
3
Find Minimum
The optimal solution uses 3 perfect squares: 4+4+4
Key Takeaway
🎯 Key Insight: This is essentially a shortest path problem where each perfect square represents a 'step' toward the target number. Dynamic Programming builds the solution bottom-up, while BFS finds the shortest path level by level.

Time & Space Complexity

Time Complexity
⏱️
O(n√n)

In worst case, we visit each number once and try √n perfect squares for each

n
2n
Linear Growth
Space Complexity
O(n)

Queue and visited set can contain up to n elements

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 104
  • n is a positive integer
  • Perfect squares include 1, 4, 9, 16, 25, 36, ...
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25
68.2K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen