Number of open doors | TCS Coding Question
Consider a long alley with N doors on one side. All the doors are closed initially. You move to and fro in the alley changing the states of the doors as follows:
- You open a door that is already closed, and you close a door that is already opened.
- You start at one end go on altering the state of the doors till you reach the other end, and then you come back and start altering the states of the doors again.
- In the first go, you alter the states of doors numbered 1, 2, 3, …, N.
- In the second go, you alter the states of doors numbered 2, 4, 6, ….
- In the third go, you alter the states of doors numbered 3, 6, 9 ….
- and so on…
The above procedure will continue till the Nth turn in which you alter the state of the door numbered N. The task is to find the number of open doors at the end of the procedure.
Input: N = 3
Input: N = 100
Approach: The given problem can be solved based on the following observations:
- A door can only be open in the end if and only if it has an odd number of factors because each door is visited once by each of its factors.
- Initially, all doors are closed so it will remain closed if it has an even number of factors and will remain open if it has an odd number of factors.
- Therefore, the total number of doors that remain open from 1 to N will be the number of doors that have an odd number of factors.
From the above observations, only the number which is perfect squares having an odd number of factors. Therefore, the total number of doors that remain open from 1 to N will be the number of perfect squares between 1 to N, and the number of perfect squares between 1 to N is sqrt(N).
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.