Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of perfect squares that sum to n.

Problem: Find the minimum number of perfect squares that sum to n.
def squares(n):
    dp = [0] + [float('inf')] * n
    for i in range(1, n + 1):
        j = 1
        while j * j <= i:
            dp[i] = min(dp[i], dp[i - j * j] + 1); j += 1
    return dp[n]
print(squares(12), squares(13), squares(7))
What is printed?
  1. A. 3 2 4
  2. B. 2 2 4
  3. C. 3 2 3
  4. D. 4 2 4

Correct answer: A. 3 2 4

12 = 4 + 4 + 4 (3), not the greedy 9 + 1 + 1 + 1 (4). 13 = 9 + 4. 7 = 4 + 1 + 1 + 1 needs 4, as Legendre's three-square theorem predicts for numbers of the form 8k + 7. O(n √n).

More Coding Interview Problems questions

Exams that ask this topic