Perfect Squares - Complete Solution Guide
Perfect Squares is LeetCode problem 279, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an integer n , return the least number of perfect square numbers that sum to n . A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1 , 4 , 9 , and 16 are perfect squares while 3 and 11 are not. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Constraints: 1 <= n <= 10 4
Detailed Explanation
The problem asks us to find the minimum number of perfect squares (e.g., 1, 4, 9, 16, ...) that sum up to a given positive integer 'n'. For example, if n = 12, the answer is 3 because 12 = 4 + 4 + 4. If n = 13, the answer is 2 because 13 = 4 + 9.
Solution Approach
The solution uses a combination of mathematical properties and a simple iterative approach to determine the minimum number of perfect squares. It first checks if 'n' is itself a perfect square. If not, it applies a transformation based on Legendre's three-square theorem and Lagrange's four-square theorem to potentially reduce the problem to finding the sum of at most three squares. Finally, it iterates through possible square numbers less than 'n' to determine if 'n' can be expressed as the sum of two squares. If none of these cases hold, it returns 3 based on Lagrange's theorem that every positive integer can be expressed as the sum of at most four squares.
Step-by-Step Algorithm
- Step 1: Check if 'n' is a perfect square. If it is, return 1.
- Step 2: Reduce 'n' by repeatedly dividing it by 4 as long as it's divisible by 4. This is based on Legendre's three-square theorem.
- Step 3: Check if the reduced 'n' is congruent to 7 modulo 8. If it is, return 4. This step utilizes Legendre's three-square theorem.
- Step 4: Iterate through all possible perfect squares less than or equal to 'n'. For each square 'i*i', check if 'n - i*i' is also a perfect square. If it is, return 2.
- Step 5: If none of the above conditions are met, return 3.
Key Insights
- Insight 1: Legendre's three-square theorem can be used to determine if a number can be represented as the sum of three squares. This is useful to avoid unnecessary computations.
- Insight 2: Lagrange's four-square theorem states that every positive integer can be expressed as the sum of at most four perfect squares.
- Insight 3: Checking if a number is already a perfect square is the first optimization and is crucial for reducing the problem to simpler cases.
Complexity Analysis
Time Complexity: O(sqrt(n))
Space Complexity: O(1)
Topics
This problem involves: Math, Dynamic Programming, Breadth-First Search.
Companies
Asked at: Accenture, Citadel, Revolut, Walmart Labs, Yandex.