Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Smallest number of perfect squares that sums up to n in JavaScript
We need to write a JavaScript function that finds the minimum number of perfect squares that sum up to a given positive number.
The function should find a combination of perfect square numbers (1, 4, 9, 16, 25, ...) which when added gives the input number, using as few perfect squares as possible.
Problem Example
If the input number is 123:
Input: 123 Output: 3
Because 123 = 121 + 1 + 1 (using three perfect squares: 11², 1², 1²)
Understanding the Pattern
This is a classic Dynamic Programming problem. We can solve it by building results for smaller numbers first. Let's see the pattern for the first few numbers:
1 ? 1 (1²) 2 ? 2 (1² + 1²) 3 ? 3 (1² + 1² + 1²) 4 ? 1 (2²) 5 ? 2 (2² + 1²) 6 ? 3 (2² + 1² + 1²)
This shows we can use preceding results to build solutions for larger numbers.
Algorithm Approach
We use dynamic programming with an array where dp[i] represents the minimum number of perfect squares needed to sum up to i.
Implementation
const num = 123;
const sumSquares = (num) => {
// dp[i] stores minimum squares needed for number i
let dp = new Array(num + 1).fill(Infinity);
dp[0] = 0; // Base case: 0 requires 0 squares
// For each number from 1 to num
for (let i = 1; i <= num; i++) {
// Try all perfect squares less than or equal to i
for (let j = 1; j * j <= i; j++) {
let square = j * j;
dp[i] = Math.min(dp[i], dp[i - square] + 1);
}
}
return dp[num];
};
console.log(sumSquares(num));
console.log(sumSquares(12)); // Test with 12 (3² + 1² + 1² + 1² = 4 squares)
console.log(sumSquares(13)); // Test with 13 (3² + 2² = 2 squares)
Output
3 4 2
How It Works
The algorithm works by:
- Creating a DP array where
dp[i]stores the minimum squares needed for numberi - For each number, trying all possible perfect squares that are ? that number
- Taking the minimum of current result and
dp[i - square] + 1 - The +1 accounts for using the current perfect square
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n?n) | For each number n, we check ?n perfect squares |
| Space | O(n) | DP array of size n+1 |
Conclusion
This dynamic programming solution efficiently finds the minimum number of perfect squares that sum to any given number. The key insight is building solutions incrementally using previously computed results.
