-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0279-perfect-squares.js
More file actions
40 lines (33 loc) · 1.19 KB
/
0279-perfect-squares.js
File metadata and controls
40 lines (33 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Perfect Squares
* Time Complexity: O(N * sqrt(N))
* Space Complexity: O(N)
*/
var numSquares = function (n) {
const numbersToExplore = [n];
const exploredNumbersSet = new Set();
exploredNumbersSet.add(n);
let currentPathLength = 0;
while (numbersToExplore.length > 0) {
currentPathLength++;
let currentLevelSize = numbersToExplore.length;
for (let currentLevelIndex = 0; currentLevelIndex < currentLevelSize; currentLevelIndex++) {
let currentNumber = numbersToExplore.shift();
for (let perfectSquareRoot = 1; ; perfectSquareRoot++) {
let squareValue = perfectSquareRoot * perfectSquareRoot;
if (squareValue > currentNumber) {
break;
}
let nextValueToReach = currentNumber - squareValue;
if (nextValueToReach === 0) {
return currentPathLength;
}
if (!exploredNumbersSet.has(nextValueToReach)) {
exploredNumbersSet.add(nextValueToReach);
numbersToExplore.push(nextValueToReach);
}
}
}
}
return -1;
};