Is this an acceptable solution to add to 100 doors?

Hi!

I just finished the 100 doors challenge and the only way I could figure it out was to manually do this exercise on paper for the first 20 doors. I know this isn’t the best approach for an interview because it was time consuming but I was banging my head against the wall with my other approaches.

function getFinalOpenedDoors(numDoors) {
    //create empty door array for final results
    let doorArr = [];
  
// I manually did the exercises for the 1st 20 doors 
//to try to find a pattern for the doors that were still open. 
//The open doors are all perfect squares.

    for(let i=1; i<=100; i++){
     if(Math.sqrt(i) % 1 === 0){
         doorArr.push(i);
     }
    }
    return doorArr;
}

Thanks!

Its the solution I’d use.

Each door is open if it is visited an odd number of times. Each door is visited once for each number that divides into it. Therefore, each open door has an odd number of divisors.

But divisors come in pairs: a / b === c means that a === b * c and b and c divide evenly into a.

So the only way to have an odd number of divisors is if for one of the pairs of divisors b === c, which means a === b * b is a perfect square.

You could be a tad more efficient with

function getFinalOpenedDoors(numDoors) {
  let doors = [];
  let i = 1, ii = i*i;

  while (ii < numDoors) {
    doors.push(ii);
    i++; ii = i*i;
  }

  return doors;
}
1 Like

Very cool. Thank you for sharing your thought process!

In an interview situation, would they expect a perspective junior to be able to solve this in like 15-20 minutes or would this be like a 45 minute time frame question.

I am not sure if this would be considered an “easy” or “medium” coding challenge by companies cause it definitely took me a while to figure this out.
Hopefully with enough practice I can figure this stuff out sooner.

Personally, this is more of a math problem than a code problem. As to interviews, I’ve never had one for a code job so I’m not sure :sweat_smile:

1 Like

I went ahead and added a solution to the Guide.

1 Like