Skip to content
Decoder

Perfect Squares

Medium

Problem

Return the least number of perfect squares (1, 4, 9, 16, ...) that sum to n. You may use the same square more than once.

Example 1

Input
n = 12
Output
3
Why
4 + 4 + 4

Example 2

Input
n = 13
Output
2
Why
4 + 9

Example 3

Input
n = 7
Output
4
Why
4 + 1 + 1 + 1

Constraints

  • 1 <= n <= 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.