Perfect Squares

Medium

Topics
MathDynamic ProgrammingBFS

Return the fewest perfect squares that add up to n. A perfect square is an integer times itself: 1, 4, 9, 16 and so on.

Squares may be repeated.

Example 1

squares available149
answer, as terms444
used in the answeravailable but not used
Writing 12 as a sum of squares needs 3 terms at fewest, shown in the lower row, and a square may repeat. Taking the largest square that fits and repeating would give 4 terms instead, so being locally frugal is a trap here rather than a shortcut.
Only the number of terms is returned, and several different sums may reach it.
Input:  n = 12
Output: 3
Explanation: 4 + 4 + 4. Using 9 instead leaves 3, which needs three 1s for four terms in total.

Example 2

squares available149
answer, as terms49
used in the answeravailable but not used
Taking the largest square that fits happens to reach the same count on this input, which it does not in general.
Input:  n = 13
Output: 2
Explanation: 4 + 9.

Example 3

squares available1
answer, as terms1
used in the answer
Input:  n = 1
Output: 1
Explanation: 1 is itself a perfect square.

Constraints

  • 1 <= n <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Taking the largest square that fits and repeating is the obvious idea and it is wrong. For n = 12 it picks 9, then 1, 1, 1 — four terms, when three 4s do it. Nothing about this problem rewards being locally frugal.

What does work is to build up the answer for every total from 1 to n. The fewest squares for a total t is one more than the fewest for t minus some square, taken over every square that fits. Each smaller total is already settled when t is reached, so each is computed once.

An equivalent view is a walk outward from n, where a step subtracts a square and every step costs the same. The first time zero is reached, it is reached in the fewest steps, and in practice that touches far fewer totals than filling the whole table.

There is also a closed-form answer. Lagrange proved every positive integer is the sum of at most four squares, and a classical result says the answer is 4 exactly when n has the form 4^k * (8m + 7); it is 1 when n is a square and 2 when n is a sum of two squares. That gives a constant-time test, though it is number theory rather than anything the problem teaches.

Approach

  1. Let fewest[t] be the answer for total t, with fewest[0] = 0.
  2. For each total t from 1 to n, consider every square j * j that is at most t.
  3. Set fewest[t] to the smallest fewest[t - j * j] + 1 over those squares.
  4. Return fewest[n].
  5. The outward-walk variant: explore from n, at each step subtracting any square that fits, and return the number of steps when zero is first reached.

Walkthrough

n = 12

fewest[0] = 0
fewest[1] = fewest[0] + 1 = 1          using 1
fewest[2] = fewest[1] + 1 = 2          1 + 1
fewest[3] = fewest[2] + 1 = 3          1 + 1 + 1
fewest[4] = min(fewest[3]+1, fewest[0]+1) = 1    using 4
fewest[5] = min(fewest[4]+1, fewest[1]+1) = 2    4 + 1
fewest[6] = 3
fewest[7] = 4
fewest[8] = min(fewest[7]+1, fewest[4]+1) = 2    4 + 4
fewest[9] = min(..., fewest[0]+1) = 1            using 9
fewest[10] = 2                                    9 + 1
fewest[11] = 3
fewest[12] = min(fewest[11]+1,                    using 1  -> 4
                 fewest[8]+1,                     using 4  -> 3
                 fewest[3]+1) = 3                 using 9  -> 4

answer 3, as 4 + 4 + 4

why taking the largest square first fails
   12 -> take 9, leaves 3
       -> 3 needs 1 + 1 + 1
       -> total 4 terms
   but 4 + 4 + 4 is 3 terms. The big square was a trap.

Complexity

  • Time — O(n * sqrt(n)): each of the n totals tries every square up to it, and there are sqrt(total) of those.
  • Space — O(n): one entry per total.

Common Pitfalls

  • Taking the largest square that fits and recursing. It gives 4 for n = 12 instead of 3.
  • Initialising the table to zero rather than to a large value, so every total reports 0.
  • Looping squares as j <= total instead of j * j <= total, which is correct but does n work per total rather than sqrt(n).
  • Forgetting fewest[0] = 0, which is what lets an exact square answer 1.
  • Reaching for the four-squares theorem without the 4^k factor in the test, which misclassifies values such as 28.

Full Solution — all languages

class Solution:
    def numSquares(self, n):
        fewest = [0] * (n + 1)

        for total in range(1, n + 1):
            best = total                 # worst case: that many 1s
            j = 1

            while j * j <= total:
                best = min(best, fewest[total - j * j] + 1)
                j += 1

            fewest[total] = best

        return fewest[n]
SensAI
Beta
Tap the mic to stop voice mode