![]() |
VOOZH | about |
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
We have discussed a generalized solution in below set 1.
Josephus problem | Set 1 (A O(n) Solution)
In this post, a special case is discussed when k = 2
Examples :
Input : n = 5 Output : The person at position 3 survives Explanation : Firstly, the person at position 2 is killed, then at 4, then at 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. Input : n = 14 Output : The person at position 13 survives
Below are some interesting facts.
If n is even and a person is in position x in current round, then the person was in position 2x - 1 in previous round.
If n is odd and a person is in position x in current round, then the person was in position 2x + 1 in previous round.
From above facts, we can recursively define the formula for finding position of survivor.
Let f(n) be position of survivor for input n, the value of f(n) can be recursively written as below. If n is even f(n) = 2f(n/2) - 1 Else f(n) = 2f((n-1)/2) + 1
Solution of above recurrence is
f(n) = 2(n - 2floor(Log2n) + 1 = 2n - 21 + floor(Log2n) + 1
Below is the implementation to find value of above formula.
The chosen place is 1
Time complexity of above solution is O(Log n).
An another interesting solution to the problem while k=2 can be given based on an observation, that we just have to left rotate the binary representation of N to get the required answer. A working code for
the same is provided below considering number to be 64-bit number.
Below is the implementation of the above approach:
The chosen place is 1
Time Complexity : O(log(n))
Auxiliary Space: O(log(n))
This idea is contributed by Anukul Chand.