![]() |
VOOZH | about |
There are N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N. The game starts going in circles counting the children starting with the first chair. Once the count reaches K, that child leaves the game, removing his/her chair. The game starts again, beginning with the next chair in the circle. The last child remaining in the circle is the winner. Find the child that wins the game. Examples:
Input : N = 5, K = 2 Output : 3 Firstly, the child at position 2 is out, then position 4 goes out, then position 1 Finally, the child at position 5 is out. So the position 3 survives. Input : 7 4 Output : 2
We have discussed a recursive solution for Josephus Problem . The given solution is better than the recursive solution of Josephus Solution which is not suitable for large inputs as it gives stack overflow. The time complexity is O(N).
Approach 1 : (Iterative Solution)
In the algorithm, we use sum variable to find out the chair to be removed. The current chair position is calculated by adding the chair count K to the previous position i.e. sum and modulus of the sum. At last we return sum+1 as numbering starts from 1 to N.
13
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2 : (Using Deque)
The intuition of using deque is quite obvious since we are traversing in a circular manner over the numbers. If we see a number which is modulus of k then remove that number from operation.
Algorithm : Push back all the numbers the deque then start traversing from the front of the deque. Keep a count of the numbers we encounter. Pop out the front element and if the count is not divisible by k then we have to push the element again from the back of deque else don't push back the element (this operation is similar to only deleting the element from the future operations). Keep doing this until the deque size becomes one.
Look at the code for better understanding.
(P.S. - Although we can skip the checking of divisible by k part by making the count again equals to zero.)
13
Time Complexity : O(N)
Auxiliary Space : O(N), for pushing the N elements in the queue.