Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
This is a classic interview question. The idea is that for any door say No. 18, the door will be toggled at the pass which is a factor of 18.
(1, 2, 3, 6, 9, 18). Now the question reduces to how many factors are there in a number.
Generally all the numbers have even number of factors because the factors pair up. For example: In case of 18, the pairs are
- 1 – 18
- 2 – 9
- 3 – 6
So the door will be ultimately closed for such numbers where the factors of the number are even.
The door will only be open for the numbers which has odd number of factors. What are these numbers?
Are they the prime numbers? No! because any prime numbers, p, will have factor 1 & p itself, hence even.
Only the perfect squares are the numbers which has odd number of factors. For example:
9
will have factors 1, 3, 9
16
will have factors 1, 2, 4, 8, 16
and so on.
Hence, the k‘th door will be open if k is a perfect square, otherwise it will be closed.
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment