DEV Community

Discussion on: The Happy Number Problem

Collapse
 
luispeerez profile image
Luis Perez Bautista

You could use Set instead of an array for seenSums, that way your validation to check the infinite loop could be done in constant time by changing

  if (seenSums.includes(sum)) return false; // generic infinite loop detection mechanism
Enter fullscreen mode Exit fullscreen mode

for

  if (seenSums.has(sum)) return false; // generic infinite loop detection mechanism
Enter fullscreen mode Exit fullscreen mode
Collapse
 
n0vum profile image
Elena Kazakova • Edited

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;
}