Perfect Squares - Problem
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
Your challenge is to find the minimum number of perfect squares that sum up to a given integer
This problem tests your ability to find optimal decompositions and can be solved using dynamic programming, BFS, or mathematical insights about number theory.
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
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
✓ Linear Growth
Space Complexity
O(n)
Queue and visited set can contain up to n elements
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 104
- n is a positive integer
- Perfect squares include 1, 4, 9, 16, 25, 36, ...
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code