KatInterview

Minimum Perfect Squares to Sum to Target

Math & Bit ManipulationAuto-graded · 22 test cases
HardAuto-gradedMath & Bit Manipulationnumber-theorymathoptimization

Last updated

Tests understanding of number theory and optimal algorithms for decomposing integers into sums of perfect squares.

Problem Statement

You are given a positive integer n. Your task is to find the smallest quantity of perfect square integers (1, 4, 9, 16, 25, ...) that add up to exactly n.

A perfect square is an integer that equals some integer multiplied by itself. For instance, 1 = 1×1, 4 = 2×2, 9 = 3×3, and so on.

Implement the following function:

def fewest_squares(n: int) -> int:

The function should return the minimum count of perfect squares needed to sum to n. You may use the same perfect square multiple times.

Constraints

  • 1 ≤ n ≤ 10^5
  • Your solution should run in O(√n) time or better

Notes

  • Every positive integer can be expressed as a sum of at most four perfect squares (this is a known mathematical theorem)
  • When n itself is a perfect square, the answer is obviously 1
  • Consider whether mathematical properties can help avoid exhaustive search

Examples

Example 1

Input: fewest_squares(12)

Output: 3

Example 2

Input: fewest_squares(13)

Output: 2

Hints

Hint 1

Check if the number itself is a perfect square first—that immediately gives you an answer of 1

Hint 2

Try checking if the number can be written as the sum of exactly two perfect squares by iterating through possible first squares

Hint 3

Use Legendre's three-square theorem: a positive integer can be expressed as a sum of three squares if and only if it is NOT of the form 4^a × (8b + 7)