Skip to content
Problem 279 · LeetCode 279(opens in a new tab)

Perfect Squares

MediumBreadth-first search

A perfect square is a whole number you get by multiplying a whole number by itself, such as 1, 4, 9 or 25.

Given a positive whole number n, return the smallest count of perfect squares that add up to exactly n. The same square may be used more than once.

Example 1

Input:  n = 8
Output: 2
Why:    8 = 4 + 4
2 more examples and the constraints

Example 2

Input:  n = 7
Output: 4
Why:    7 = 4 + 1 + 1 + 1; no shorter sum works

Example 3

Input:  n = 25
Output: 1
Why:    25 is itself a square

Constraints

  • 1 ≤ n ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. BFS on what is leftO(n√n)
  2. Bottom-up DPO(n√n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10,000Verdict
BFS on what is leftO(n√n)
Passes; more moving parts
Bottom-up DPO(n√n)
Best; short and predictable

n = the target number; √n is how many squares fit under it. BFS can stop early, DP always fills the table.

Edge cases to test

  • n is a square. 25 or 10,000 gives 1.
  • n = 1. The smallest input is itself a square: 1.
  • Needs four. 7 and 9,999 cannot be done with three squares.
  • Greedy fails. For 12, taking 9 first gives 9 + 1 + 1 + 1 (four), but 4 + 4 + 4 needs only three.

Common mistakes

  • Taking the largest square first. That greedy choice is wrong for 12.
  • Starting the table with 0 everywhere instead of ∞, so every minimum comes out 1.
  • Looping j while j ≤ i instead of j * j ≤ i, which reads negative indices.

How to talk through it

  1. 1Clarify. Can a square repeat? Is n always at least 1? How large can n get?
  2. 2Rule out greedy. Show 12: the largest square first gives four, the best is three.
  3. 3Find the subproblem. Strip the last square j²; the rest, i − j², should also be as short as possible.
  4. 4Code the table. dp[0] = 0, the rest ∞, fill i from 1 to n trying each j² ≤ i.
  5. 5Test out loud. Run 1, 7, 8 and 12 and check each against a hand count.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?