Perfect Squares

Find the fewest perfect squares that add up to a number, using the answers for every smaller number.

Given an integer n, return the least number of perfect squares that add up to n. A perfect square is a whole number times itself, such as 1, 4, 9 or 16. The same square may be used more than once.

Example 1
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
Solution

The Idea

Imagine a shop whose coins are worth 1, 4, 9, 16 and so on, one coin for every perfect square. You have to pay 12, and you want to hand over as few coins as possible.

The natural plan is to take the biggest coin that fits, then repeat. For 12 that is 9, and the 3 left over can only be paid as 1 + 1 + 1, so four coins in all. Yet 4 + 4 + 4 pays 12 with three. Taking the biggest coin each time is called a greedy choice, and here it loses: the 9 leaves a remainder, 3, that costs three more coins.

So how do we know which squares to use, without trying every mix of them? Turn the question around and look at the last square in the sum. If the last one is 4, the rest adds up to 8, and paying 8 with the fewest squares is the same problem with a smaller number. The best answer for 12 is therefore one square plus the best answer for 12 - 1, 12 - 4 or 12 - 9, whichever is smallest.

That needs the answers for smaller numbers first, so we keep them in a table. Its entry for a number i is called dp[i]: the fewest perfect squares that add up to i. The first entry, dp[0], is 0, since making 0 needs no squares at all. Look at the picture below.

The table for n = 12. The row labelled number i runs from 0 to 12, and the row labelled fewest squares dp[i] holds 0, 1, 2, 3, 1, 2, 3, 4, 2, 1, 2, 3, 3. Three arrows lead into 12: last square 1 from dp[11] gives 3 + 1 = 4, last square 4 from dp[8] gives 2 + 1 = 3, last square 9 from dp[3] gives 3 + 1 = 4. The smallest, 3, is dp[12].

The row labelled number i runs from 0 to 12, and the row below it holds dp[i] for each one. Three arrows lead into 12, one for each square that fits. The arrow marked last square 1 starts at dp[11], which is 3, so that way takes 3 + 1 = 4 squares. The arrow marked last square 9 starts at dp[3] and also gives 4.

The orange arrow, last square 4, starts at dp[8], which is 2, because 8 = 4 + 4. It gives 2 + 1 = 3, the smallest of the three, so dp[12] is 3. Working out dp[12] from the stored entries for 11, 8 and 3, instead of solving those smaller numbers again, is called dynamic programming.

Solution Approach

Trying every mix of squares works but repeats itself. The table avoids that once three things are settled: the order its entries are filled in, which squares each entry tries, and what it holds at the start.

Trying every mix of squares

Why not simply try every way to write n as a sum of squares? A search could pick a last square, then a last square for what remains, and so on down to 0. The trouble is that the same leftovers come up again and again. Taking 4 and then 4 from 12 leaves 4, and so does taking 1 four times and then 4. Without a table, the search works out the answer for 4 once for every path that reaches it.

Filling the table in order

In which order should the entries be filled? The entry dp[i] reads only entries for smaller numbers, i - 1, i - 4, i - 9 and so on. Filling the table from 1 up to n means every entry that dp[i] reads is already finished when i is reached.

Which squares to try

Which squares does dp[i] try as the last one? Every k * k that is at most i, for k = 1, 2, 3 and so on. The check allows k * k to equal i, so dp[4] tries the square 4 itself, reads dp[0], and gets 1. The square 1 always fits, so every number can be made, from 1s if nothing better exists.

Starting values

What does the table hold before an entry is worked out? The entry dp[0] is 0, and every other entry starts at Integer.MAX_VALUE, the largest value a Java int can take. Any real count is smaller, so the first square tried for an entry always replaces that starting value.

Java Solution

The method numSquares works in these steps:

  1. First, create the table dp with n + 1 entries, one for each number from 0 to n. Fill it with Integer.MAX_VALUE using Arrays.fill, and set dp[0] to 0.
  2. Work out the entries with two loops, one inside the other. The outer loop moves i from 1 to n, the number whose entry is being worked out.
  3. For each i, the inner loop moves k up from 1 while k * k is at most i. For each square k * k, the count dp[i - k * k] + 1 is one candidate, and Math.min keeps the smaller of it and the current dp[i].
  4. When the outer loop is done, dp[n] holds the fewest squares for n, and the method returns it.

The main method runs both examples, then 1, 7, 43 and 10,000.

Java
import java.util.Arrays;

public class PerfectSquares {

    public static int numSquares(int n) {
        int[] dp = new int[n + 1];          // dp[i]: fewest perfect squares that add up to i
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;                          // 0 needs no squares at all
        for (int i = 1; i <= n; i++) {
            for (int k = 1; k * k <= i; k++) {
                dp[i] = Math.min(dp[i], dp[i - k * k] + 1);   // k * k is the last square
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        System.out.println("n = 12: " + numSquares(12));
        System.out.println("n = 13: " + numSquares(13));
        System.out.println("n = 1: " + numSquares(1));
        System.out.println("n = 7: " + numSquares(7));
        System.out.println("n = 43: " + numSquares(43));
        System.out.println("n = 10000: " + numSquares(10000));
    }
}

Running it prints:

Output
n = 12: 3
n = 13: 2
n = 1: 1
n = 7: 4
n = 43: 3
n = 10000: 1

The answer 3 for n = 12 is the 4 + 4 + 4 from the orange arrow, and 13 needs 2, from 4 + 9. For n = 7 the answer is 4: only the squares 1 and 4 fit under 7, and 7 = 4 + 1 + 1 + 1.

The line n = 43: 3 comes from 25 + 9 + 9. Taking the biggest square first would start with 36 and then pay the 7 left over with 4 + 1 + 1 + 1, five squares in all. The last line is 1, because 10,000 is 100 × 100: the inner loop reaches k = 100 and reads dp[0].

The check k * k <= i matters. With k * k < i, no square fits under 1, so dp[1] stays Integer.MAX_VALUE. Then dp[2] adds 1 to it, which wraps around to a negative number, and that number spreads through the table. In a run of that version, numSquares(4) returned -2147483646.

Complexity

The work is one pass over the numbers 1 to n, with a short loop over squares for each.

  • Time: O(n √n), because each of the n entries tries every square up to its own number, and there are at most √n of those.
  • Space: O(n), because the table keeps one count for each number from 0 to n.

No entry ever goes above 4. Every whole number is a sum of at most four squares, a result known as Lagrange's four-square theorem, and 7 is the smallest number that needs all four. Further results from number theory tell which numbers need exactly four, and they lead to an O(√n) check, but the table needs none of that theory.

The same table, with any set of coin values in place of the squares, solves Coin Change.