Skip to content

ORIGINAL CODING QUESTION

Fewest square-valued tokens

Return the minimum number of positive perfect squares that sum to x. Squares may repeat; x=0 needs zero tokens.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

One nonnegative integer x.

Constraints

0 ≤ x ≤ 1000.

Example 1

Input

12

Output

3

Three value-4 tokens suffice.

Example 2

Input

13

Output

2

Values 4 and 9 use two tokens.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Every square defines a possible last token.

Hint 2

Store the fewest tokens for each smaller sum.

Hint 3

dp[s]=min(dp[s-square]+1) over valid squares.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →