![]() |
VOOZH | about |
Given that N person (numbered 1 to N) standing to form a circle. They all have the gun in their hand which is pointed to their leftmost Partner.
Everyone shoots such that 1 shoots 2, 3 shoots 4, 5 shoots 6 .... (N-1)the shoot N (if N is even otherwise N shoots 1).
Again on the second iteration, they shoot the rest of the remains as above mentioned logic (now for n as even, 1 will shoot to 3, 5 will shoot to 7, and so on).
The task is to find which person is the luckiest(didn't die).
Examples:
Input: N = 3
Output: 3
As N = 3 then 1 will shoot 2, 3 will shoot 1 hence 3 is the luckiest person.Input: N = 8
Output: 1
Here as N = 8, 1 will shoot 2, 3 will shoot 4, 5 will shoot 6, 7 will shoot 8, Again 1 will shoot 3, 5 will shoot 7, Again 1 will shoot 5 and hence 1 is the luckiest person.
This problem has already been discussed in Lucky alive person in a circle | Code Solution to sword puzzle. In this post, a different approach is discussed.
Approach:
Below is the implementation of the above approach:
3
Alternate Shorter Implementation :
The approach used here is same.
3
Alternate Implementation in O(1) : The approach used here is same, but the operations used are of constant time.
1
Another approach in O(1) : On the basis of the pattern that forms in given question, which is displayed in following table.
| n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 1 | 1 | 3 | 1 | 3 | 5 | 7 | 1 | 3 | 5 | 7 | 9 | 11 | 13 | 15 | 1 |
3