Perfect Squares

Perfect Squares is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Dynamic Programming (DP) Patterns pattern, in the 1D Array (Coin Change / Unbounded Knapsack Style) subpattern.

Problem statement

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

Topics and companies

Topics: Dynamic Programming, Math, Array.

How to practise Perfect Squares on Thita.ai

Starter code is provided in C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n * sqrt(n)) time and O(n) space.

Open Perfect Squares in the code editor, or read the Perfect Squares editorial for a worked solution with its approach and complexity analysis.

Where Perfect Squares sits in the DSA pattern sheet

Problems related to Perfect Squares

Other problems that use the same 1D Array (Coin Change / Unbounded Knapsack Style) and Dynamic Programming (DP) Patterns techniques:

Preparing this workspace.