Skip to main content

Perfect Squares

Medium
Data Structures and Algorithms
Editorial
Topics:
Dynamic Programming
Math
Array

Given a positive integer n, consider the set of perfect squares that do not exceed n. A perfect square is the product of an integer with itself, such as 1, 4, 9, or 16.

Determine the smallest number of perfect-square terms whose sum is exactly n. A square may be used more than once, and the order of the terms does not matter.

Return that minimum number as an integer.

Example 1:

Input: n = 7
Output: 4
Explanation: The minimum representation is 4 + 1 + 1 + 1, which uses four perfect squares.

Example 2:

Input: n = 18
Output: 2
Explanation: 18 can be written as 9 + 9, so two perfect squares suffice.

Example 3:

Input: n = 26
Output: 2
Explanation: 26 equals 25 + 1, and it cannot itself be represented by one perfect square.

Constraints:

  • 1 <= n <= 10^4
  • n is an integer
  • Only positive perfect squares less than or equal to n may be used
  • At least one representation of n as a sum of positive perfect squares exists

Need help or want more practice?

Practise in an interviewGet AI Coach help