279. Perfect Squares - Detailed Explanation
Problem Statement
Given a positive integer n, find the smallest number of perfect square numbers (e.g. 1, 4, 9, 16, …) whose sum equals n. Return that minimum count.
Examples
Input n = 12
Output 3
Explanation 12 = 4 + 4 + 4
Input n = 13
Output 2
Explanation 13 = 4 + 9
Constraints
- 1 ≤ n ≤ 10⁴
Hints
- You can view the problem as finding the shortest path from
ndown to 0 by subtracting squares. - For dynamic programming, think about how the solution for
ndepends on smaller valuesn - k². - A theorem says every positive integer is the sum of at most four squares—can you use that to shortcut for some cases?
Approach 1 – BFS over States
You can treat each integer x from n down to 0 as a node; edges go from x to x - k² for all k² ≤ x. A breadth‑first search from n stops at 0 with the shortest distance equal to the answer.
Python Code
Python3
Python3
. . . .
- Time: O(n √n) in practice
- Space: O(n) for the queue and visited set
Approach 2 – Dynamic Programming
Define dp[i] = minimum number of squares summing to i. Then
dp[0] = 0
for i in 1…n:
dp[i] = min(dp[i - k²] + 1 for k² ≤ i)
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
- Time: O(n √n)
- Space: O(n)
Approach 3 – Mathematical Theorem (Lagrange’s Four‑Square)
A classic result says every natural number is the sum of at most four squares. You can check in O(√n) time whether it is 1‑, 2‑, or 3‑square representable; otherwise the answer is 4.
- If
nis a perfect square → return 1. - Remove factors of 4 from
n(while divisible by 4, divide by 4). - If
n ≡ 7 mod 8→ return 4. - Check if
n = a² + b²for somea,b→ return 2. - Otherwise → return 3.
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
- Time: O(√n)
- Space: O(1)
Complexity Analysis
- BFS/DP: O(n √n), O(n) space
- Math: O(√n), O(1) space
Step‑by‑Step Walkthrough (n = 12)
- DP:
- dp[1]=1, dp[2]=2, dp[3]=3, dp[4]=1, … dp[12]=dp[12‑9]+1=dp[3]+1=4 → but a better is dp[12‑4]+1=dp[8]+1= (dp[8‑4]+1)+1 = … =3
- Math:
- 12 not square, not ≡7 mod8 after dividing by 4⁰, check two‑square: 12–1²=11 not square, 12–2²=8 not square, 12–3²=3 not square → return 3.
Common Mistakes
- Forgetting to initialize dp[0]=0.
- In DP, iterating
jtoo far (stop when j²>i). - In math approach, skipping the “remove factors of 4” step and misclassifying 28 as 4‑case.
Edge Cases
- n=1 → 1
- n a perfect square (e.g. 16) → 1
- n=2 or 3 → equals itself as two or three 1²’s
- Large n up to 10⁴ → DP/BFS safe; math is fastest.
Alternative Variations
- Count how many representations as sum of squares exist.
- Find one actual decomposition into squares.
- Generalize to higher powers (cubes, etc.)—harder open problems.
Related Problems
- 64. Minimum Path Sum – DP over grid with min‑sum recurrence.
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
2877. Create a DataFrame from List - Detailed Explanation
Learn to solve Leetcode 2877. Create a DataFrame from List with multiple approaches.
723. Candy Crush - Detailed Explanation
Learn to solve Leetcode 723. Candy Crush with multiple approaches.
1216. Valid Palindrome III - Detailed Explanation
Learn to solve Leetcode 1216. Valid Palindrome III with multiple approaches.
1574. Shortest Subarray to be Removed to Make Array Sorted - Detailed Explanation
Learn to solve Leetcode 1574. Shortest Subarray to be Removed to Make Array Sorted with multiple approaches.
143. Reorder List - Detailed Explanation
Learn to solve Leetcode 143. Reorder List with multiple approaches.
1942. The Number of the Smallest Unoccupied Chair - Detailed Explanation
Learn to solve Leetcode 1942. The Number of the Smallest Unoccupied Chair with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
$197
New

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.