Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Input & Output

Example 1 — Basic Case
$ Input: n = 12
Output: 3
💡 Note: 12 = 4 + 4 + 4. We need 3 perfect squares (each is 2²), so return 3.
Example 2 — Single Square
$ Input: n = 13
Output: 2
💡 Note: 13 = 9 + 4 = 3² + 2². We need 2 perfect squares, so return 2.
Example 3 — Already Perfect Square
$ Input: n = 16
Output: 1
💡 Note: 16 = 4² is already a perfect square, so we need only 1 perfect square.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Perfect Squares Problem: Find Minimum Squares for n=12Inputn = 12Available Perfect Squares1, 4, 9, 16, 25, ...Output3Possible Combinations:1+1+1+...+1 = 12(12 squares)9+1+1+1 = 12(4 squares)4+4+4 = 12(3 squares) ✓Minimum: 12 = 4 + 4 + 4 → 3 perfect squaresGoal: Find the combination with minimum count
Understanding the Visualization
1
Input
Given integer n = 12
2
Process
Find minimum perfect squares that sum to 12
3
Output
Return 3 (since 12 = 4 + 4 + 4)
Key Takeaway
🎯 Key Insight: Use dynamic programming to build optimal solutions for each number from 1 to n
Asked in
Google 45 Amazon 38 Facebook 25 Microsoft 20
67.0K Views
High Frequency
~25 min Avg. Time
1.9K 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