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 - Dynamic Programming INPUT n = 12 Target sum Perfect Squares <= 12 1 1x1 4 2x2 9 3x3 Find minimum count of squares summing to 12 12 = 4 + 4 + 4 (3 squares) 12 = 9 + 1 + 1 + 1 (4 squares) 12 = 1+1+...+1 (12 squares) ALGORITHM STEPS 1 Initialize DP Array dp[0]=0, dp[i]=infinity 2 For i = 1 to n Try each perfect square j*j 3 Update dp[i] dp[i] = min(dp[i], dp[i-j*j]+1) 4 Return dp[n] Minimum squares needed DP Table (partial) i dp 0 0 1 1 2 2 3 3 4 1 ... ... 12 3 dp[12] = min(dp[12-1]+1, dp[12-4]+1, dp[12-9]+1) = min(4,3,4) = 3 Time: O(n * sqrt(n)) FINAL RESULT Optimal decomposition of 12: 4 2x2 + 4 2x2 + 4 4 + 4 + 4 = 12 Output: 3 OK - Minimum! 3 perfect squares is optimal (cannot do better) Key Insight: DP builds optimal solutions from smaller subproblems. For each number i, we try subtracting each perfect square j*j and take the minimum: dp[i] = min(dp[i-j*j] + 1) for all valid j. This ensures we find the minimum count by leveraging previously computed optimal values. TutorialsPoint - Perfect Squares | Dynamic Programming Approach
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