VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-door-open-closed/

⇱ Check if the door is open or closed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if the door is open or closed

Last Updated : 21 Mar, 2025

Given n doors and n persons. The doors are numbered 1 to n and persons are given id's numbered 1 to n. Each door can have only 2 status open and closed. Initially all the doors have status closed.
Find the final status of all the doors if a person changes the current status of all the doors, i.e. if status open then change to status closed and vice versa, for which he is authorized. A person with id 'i' is authorized to change the status of door numbered 'j' if 'j' is a multiple of 'i'. 

Note: 

  • Initially all the doors have status closed.
  • A person has to change the current status of all the doors for which he is authorized exactly once. 
  • There can be a situation that before a person changes the status of the door, another person who is also authorized for the same door changes the status of the door. 

Example :

Input 3
Output open closed closed
Explanation
The person with id 1 opens all doors : open open open
id 2 closes the second door : open closed open
id 3 closes the third door : open closed closed

Input 4
Output open closed closed openclosed closed closed
Explanation
The person with id 1 opens all doors : open open open open
id 2 closes the 2nd and 4th doors : open closed open closed
id 3 closes the third door : open closed closed closed
id 4 opens the fourth door : open closed closed open

[Naive Approach] Using Nested Loop – O(n2) time and O(1) space

Each door is toggled once for every divisor of its number. Doors with an odd number of divisors remain open, and doors with an even number of divisors remain closed. Only perfect square doors (1, 4, 9, 16, 25, ...) have an odd number of divisors, so they remain open. Please note that, for every number, divisors appear in pairs. For example, 12 has divisors (1, 12), (3, 4) and (2, 6). For a perfect square, there is a pair that has same values and this makes the number of different divisors odd. For example for 16, divisors are (1, 16), (2, 8) and (4, 4)


Output
open closed closed open closed 

[Expected Approach] Finding Square Root – O(n log(n)) time and O(1) space

We can use Check if count of divisors is even or odd logic to solve the problem effectively.


Output
open closed closed open closed 
Comment
Article Tags: