Can you please explain why the solution with new Setdoes not pass in time (Time Limit Exceeded)?
This is OK: var isHappy = function(n) {
var map = {};
var tmp = 0;
if (n < 1) return false;
while (n !== 1 && !map[n]) {
map[n] = true;
tmp = 0;
while (n > 0) {
tmp += Math.pow(n % 10, 2);
n = Math.floor(n / 10);
}
n = tmp;
}
return n === 1;
};
This is not OK: var isHappy = function(n) {
function sumSquares(n) {
let sum = 0;
while (n > 0) {
sum += (n % 10) ** 2;
num = Math.floor(n / 10);
}
return sum;
}
const seen = new Set();
while (n != 1 && !seen.has(n)) {
seen.add(n);
n = sumSquares(n);
}
return num == 1;
}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You could use
Set
instead of an array forseenSums
, that way your validation to check the infinite loop could be done in constant time by changingfor
Can you please explain why the solution with
new Set
does not pass in time (Time Limit Exceeded)?This is OK:
var isHappy = function(n) {
var map = {};
var tmp = 0;
if (n < 1) return false;
while (n !== 1 && !map[n]) {
map[n] = true;
tmp = 0;
while (n > 0) {
tmp += Math.pow(n % 10, 2);
n = Math.floor(n / 10);
}
n = tmp;
}
return n === 1;
};
This is not OK:
var isHappy = function(n) {
function sumSquares(n) {
let sum = 0;
while (n > 0) {
sum += (n % 10) ** 2;
num = Math.floor(n / 10);
}
return sum;
}
const seen = new Set();
while (n != 1 && !seen.has(n)) {
seen.add(n);
n = sumSquares(n);
}
return num == 1;
}