Perfect Squares
Problem Statement
You are given a whole number n. A perfect square is a number like 1, 4, 9, 16 and so on, which is a whole number multiplied by itself.
Find the fewest perfect squares that add up to exactly n. A square can be used more than once.
Return that smallest count.
A whole number n.
The fewest perfect squares whose sum is n.
12 = 4 + 4 + 4. No two squares make 12 (for example 9 + 3 and 4 + 8 do not work), so 3 is the least.
13 = 4 + 9. 13 is not a square itself, so one square is not enough.
- • 1 ≤ n ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For an amount left, try every square that fits, then solve the smaller amount
dp[i] = 1 + the best dp[i − k·k] over every square ≤ i; fill from 0 up to n
For an amount left, ask how few squares make it. Try every square k·k that is at most left. Take it, and ask the same question for left − k·k. Add one for the square taken, and keep the smallest total. When left is 0, no squares are needed.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — 1D Linear translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.