Ctrl K

Fewest Square Terms

Medium
You are given a positive integer total. Write it as a sum of perfect squares (1, 4, 9, 16, …) using as few terms as possible. Any square may be used any number of times. Return the smallest possible number of terms.
Example 1
total=18 → 2

18 = 9 + 9. One square is not enough, since 18 itself is not a square.

Example 2
total=7 → 4

7 = 4 + 1 + 1 + 1; no shorter sum exists.

Example 3
total=49 → 1

49 = 7², so a single term is enough.

Constraints
  • 1 ≤ total ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCounting Grid Routes MediumCounting Search Tree Shapes MediumEvery Bracketing Result MediumNumbers Made of Twos, Threes and Fives MediumNth Number Built From Given Primes Medium
loading Python…
Input
total=18
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 77 tests on the server, hidden ones included.