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.
// Iterative solution for Josephus Problem #include <bits/stdc++.h> using namespace std;
// Function for finding the winning child. long long int find( long long int n, long long int k)
{ long long int sum = 0, i;
// For finding out the removed
// chairs in each iteration
for (i = 2; i <= n; i++)
sum = (sum + k) % i;
return sum + 1;
} // Driver function to find the winning child int main()
{ int n = 14, k = 2;
cout << find(n, k);
return 0;
} |
// Iterative solution for Josephus Problem class Test
{ // Method for finding the winning child.
private int josephus( int n, int k)
{
int sum = 0 ;
// For finding out the removed
// chairs in each iteration
for ( int i = 2 ; i <= n; i++)
{
sum = (sum + k) % i;
}
return sum+ 1 ;
}
// Driver Program to test above method
public static void main(String[] args)
{
int n = 14 ;
int k = 2 ;
Test obj = new Test();
System.out.println(obj.josephus(n, k));
}
} // This code is contributed by Kumar Saras |
# Iterative solution for Josephus Problem # Function for finding the winning child. def find(n, k):
sum = 0
# For finding out the removed
# chairs in each iteration
for i in range ( 2 ,n + 1 ):
sum = ( sum + k) % i
return sum + 1
# Driver function to find the winning child n,k = 14 , 2
print (find(n, k))
# This code is contributed by shinjanpatra |
// Iterative solution for Josephus Problem using System;
class Test
{ // Method for finding the winning child.
private int josephus( int n, int k)
{
int sum = 0;
// For finding out the removed
// chairs in each iteration
for ( int i = 2; i <= n; i++)
{
sum = (sum + k) % i;
}
return sum+1;
}
// Driver Program to test above method
public static void Main(String[] args)
{
int n = 14;
int k = 2;
Test obj = new Test();
Console.WriteLine(obj.josephus(n, k));
}
} // This code is contributed by Aman Kumar |
<script> // Iterative solution for Josephus Problem // Function for finding the winning child. function find(n, k)
{ let sum = 0, i;
// For finding out the removed
// chairs in each iteration
for (i = 2; i <= n; i++)
sum = (sum + k) % i;
return sum + 1;
} // Driver function to find the winning child let n = 14, k = 2; document.write(find(n, k), "</br>" );
// This code is contributed by shinjanpatra </script> |
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.)
// Iterative solution for Josephus Problem #include <bits/stdc++.h> using namespace std;
// Function for finding the winning child. long long int find( long long int n, long long int k)
{ deque< long long int > dq;
// push back all the elements in deque
for ( long long int i = 1; i <= n; i++)
dq.push_back(i);
// keeping the counter variable
long long int count = 0;
while (dq.size() > 1) {
// push out the front element
long long int curr = dq.front();
// pop out the front element
dq.pop_front();
// increment the count
count++;
// if the count is divisible by k
// then don't have to push back again
if (count % k == 0)
continue ;
// else push back the element
// for future operations
dq.push_back(curr);
}
// the only element left in queue
// is the answer
return dq.back();
} // Driver function to find the winning child int main()
{ int n = 14, k = 2;
cout << find(n, k);
return 0;
} // this code is contributed by rajdeep999 |
// Java Equivalent import java.util.Deque;
import java.util.LinkedList;
public class Test {
// Function for finding the winning child.
public static int find( int n, int k) {
Deque<Integer> dq = new LinkedList<Integer>();
// push back all the elements in deque
for ( int i = 1 ; i < n+ 1 ; i++) {
dq.add(i);
}
// keeping the counter variable
int count = 0 ;
while (dq.size() > 1 ) {
// push out the front element
int curr = dq.peek();
// pop out the front element
dq.removeFirst();
// increment the count
count++;
// if the count is divisible by k
// then don't have to push back again
if (count % k == 0 ) {
continue ;
}
// else push back the element
// for future operations
dq.add(curr);
}
// the only element left in queue
// is the answer
return dq.peekLast();
}
// Driver function to find the winning child
public static void main(String[] args) {
int n = 14 ;
int k = 2 ;
System.out.println(find(n, k));
}
} |
# Iterative solution for Josephus Problem from collections import deque
# Function for finding the winning child. def find(n, k):
dq = deque()
# push back all the elements in deque
for i in range ( 1 , n + 1 ):
dq.append(i)
# keeping the counter variable
count = 0
while len (dq) > 1 :
# push out the front element
curr = dq[ 0 ]
# pop out the front element
dq.popleft()
# increment the count
count + = 1
# if the count is divisible by k
# then don't have to push back again
if count % k = = 0 :
continue
# else push back the element
# for future operations
dq.append(curr)
# the only element left in queue
# is the answer
return dq[ - 1 ]
# Driver function to find the winning child if __name__ = = '__main__' :
n = 14
k = 2
print (find(n, k))
|
using System;
using System.Collections.Generic;
class Test {
// Function for finding the winning child.
public static int Find( int n, int k) {
Queue< int > dq = new Queue< int >();
// push back all the elements in deque
for ( int i = 1; i < n + 1; i++) {
dq.Enqueue(i);
}
// keeping the counter variable
int count = 0;
while (dq.Count > 1) {
// push out the front element
int curr = dq.Peek();
// pop out the front element
dq.Dequeue();
// increment the count
count++;
// if the count is divisible by k
// then don't have to push back again
if (count % k == 0) {
continue ;
}
// else push back the element
// for future operations
dq.Enqueue(curr);
}
// the only element left in queue
// is the answer
return dq.Peek();
}
// Driver function to find the winning child
static void Main( string [] args) {
int n = 14;
int k = 2;
Console.WriteLine(Find(n, k));
}
} |
function find(n, k) {
const dq = [];
// push back all the elements in deque
for (let i = 1; i <= n; i++) {
dq.push(i);
}
// keeping the counter variable
let count = 0;
while (dq.length > 1)
{
// push out the front element
const curr = dq.shift();
// increment the count
count++;
// if the count is divisible by k
// then don't have to push back again
if (count % k === 0) {
continue ;
}
// else push back the element
// for future operations
dq.push(curr);
}
// the only element left in queue
// is the answer
return dq[0];
} // Driver function to find the winning child const n = 14, k = 2; console.log(find(n, k)); |
13
Time Complexity : O(N)
Auxiliary Space : O(N), for pushing the N elements in the queue.