Tensorum
LeetCode 279 · Unbounded Knapsack

Perfect Squares

LeetCode 279 · Medium · solution, intuition & step-by-step walkthrough

dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.

MediumMathDynamic ProgrammingBreadth-First SearchKnapsack ProblemComplete Knapsack
2270 msruntime · beats 21%
17.8 MBmemory · beats 100%
1approach
9accepted runs · last 8 May 2025

This is how I solved Perfect Squares (LeetCode 279), a medium problem from the Unbounded Knapsack pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Treat each perfect square as a coin you can use as often as you like, and ask for the fewest coins that add up to n. dp[x] is the fewest squares for x, built from dp[x − s] + 1 over every square s ≤ x.

Approach

  1. 1

    List the squares 1, 4, 9, … up to n.

  2. 2

    dp[0] = 0.

  3. 3

    For each x from 1 to n, try every square that fits and keep the minimum.

  4. 4

    Return dp[n].

How I solved it

Tabulation over nPythonO(n√n) time · O(n) space
class Solution:
    def numSquares(self, n: int) -> int:
        squares =[i**2 for i in range(1,int(math.sqrt(n))+1)]
        # def dfs(cur_num):
        #     if cur_num in squares:
        #         return 1
        #     min_count=float("inf")
        #     for square in squares:
        #         if square>cur_num:
        #             break
        #         cur_count=dfs(cur_num-square)+1
        #         min_count=min(min_count,cur_count)
        #     return min_count
        # return dfs(n)
        dp=[float("inf")]*(n+1)
        dp[0]=0
        for cur_num in range(1,n+1):
            min_count=float("inf")
            for square in squares:
                if square>cur_num:
                    break
                cur_count=dp[cur_num-square]+1
                min_count=min(min_count,cur_count)
                dp[cur_num]=min_count
        return dp[n]
Loading the step-through…

Perfect Squares — FAQ

What is the intuition behind Perfect Squares?

Treat each perfect square as a coin you can use as often as you like, and ask for the fewest coins that add up to n. dp[x] is the fewest squares for x, built from dp[x − s] + 1 over every square s ≤ x.

How do you solve Perfect Squares (LeetCode 279)?

1. List the squares 1, 4, 9, … up to n. 2. dp[0] = 0. 3. For each x from 1 to n, try every square that fits and keep the minimum. 4. Return dp[n].

What is the time and space complexity of Perfect Squares?

Time: O(n · √n). Space: O(n). (Accepted approach: Tabulation over n.)

What are common mistakes in Perfect Squares?

Break out of the squares loop once a square exceeds x. Lagrange's four-square theorem caps the answer at 4 — a neat sanity check.