0:00 / 0:00

Fewest squares that sum to n: build a table up from zero, trying every square that fits. It's Coin Change with squares as coins.

▼

The problem

LeetCode 279 (Medium). Given an integer n, return the least number of perfect squares (1, 4, 9, 16, ...) that sum to n.

Example (LeetCode's): n = 12 → 3 (4 + 4 + 4).

from math import inf, isqrt
def num_squares(n):
    squares = [k * k for k in range(1, isqrt(n) + 1)]
    dp = [0] + [inf] * n
    for i in range(1, n + 1):
        for s in squares:
            if s > i:
                break
            dp[i] = min(dp[i], dp[i - s] + 1)
    return dp[n]
TRY IT ON LEETCODE ▶

The solution

from math import inf, isqrt
def num_squares(n):
    squares = [k * k for k in range(1, isqrt(n) + 1)]
    dp = [0] + [inf] * n
    for i in range(1, n + 1):
        for s in squares:
            if s > i:
                break
            dp[i] = min(dp[i], dp[i - s] + 1)
    return dp[n]

Transcript

Perfect Squares. Given a number n, find the fewest perfect squares that add up to it. A perfect square is a number times itself: one, four, nine, sixteen. Think of each one as a square quilt patch.

Take twelve. Four plus four plus four makes twelve: three squares. Grabbing the biggest square first fails: nine leaves three, which takes three ones. That's four squares, not three.

So try everything. From twelve, take away each square that fits: one, four or nine. That leaves eleven, eight or three, and each of those branches again. Three alone gets solved eleven times, and twelve takes a hundred and four calls. That grows exponentially.

Instead, solve each number once, from the bottom up. Keep a table: entry i is the fewest squares that add up to i. Zero needs none. For any i, try each square that fits. Take it away, look up the best for what's left, and add one. Keep the smallest. It's Coin Change, with squares as the coins.

In code, fill the table with infinity, except zero at the start. For each i, loop over the squares until one is bigger than i. Keep the smaller of the entry and one plus the entry for i minus the square. Return the entry for n.

Let's fill it for twelve. One, two and three need that many ones. Four is a square: one. Five, six and seven add ones: two, three, four. Eight is two fours, nine is one, ten is two, eleven is three. Now twelve. Take a one: eleven needs three, so four. Take a four: eight needs two, so three. Take a nine: three needs three, so four. The best is three: four plus four plus four.

Each of the n entries tries at most root n squares: order n root n time. The table holds n plus one numbers: order n space.

Start from zero, try every square, keep the fewest. That's Perfect Squares.