Imagine you want to represent a number as a sum of perfect squares, like breaking a chocolate bar into square pieces with minimal cuts.
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 (e.g., 1, 4, 9, 16, ...). Input: integer n. Output: integer representing the minimum count of perfect squares summing to n.
1 ≤ n ≤ 10^5
Edge cases: n = 1 → output 1 (smallest input)n = 0 → output 0 (no squares needed)n = 10000 → output 1 (perfect square itself)
def numSquares(n: int) -> int:public int numSquares(int n)int numSquares(int n)function numSquares(n)
def numSquares(n):
# Write your solution here
pass
class Solution {
public int numSquares(int n) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int numSquares(int n) {
// Write your solution here
return 0;
}
function numSquares(n) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 1Greedy approach picking largest square once, ignoring multiple usage.✅ Iterate over all squares j*j <= i and update dp[i] = min(dp[i], 1 + dp[i - j*j]) allowing repeated use.
Wrong: 3Confusing 0/1 knapsack with unbounded knapsack, using each square only once.✅ Allow multiple usage by using unbounded knapsack recurrence: dp[i] = min(dp[i], 1 + dp[i - j*j]) for all j.
Wrong: 0Missing base case for n=0 or incorrect initialization.✅ Set dp[0] = 0 explicitly to handle zero input correctly.
Wrong: 2Off-by-one error in dp array indexing or incomplete iteration.✅ Ensure dp array covers all indices from 0 to n inclusive and loops run correctly.
Wrong: TLEUsing brute force recursion without memoization or bottom-up DP.✅ Implement bottom-up DP with precomputed squares to achieve O(n * sqrt(n)) time.