Perfect Squares - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code