Josephus Problem | (Iterative Solution)
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.
C++
#include <bits/stdc++.h>
using namespace std;
long long int find( long long int n, long long int k)
{
long long int sum = 0, i;
for (i = 2; i <= n; i++)
sum = (sum + k) % i;
return sum + 1;
}
int main()
{
int n = 14, k = 2;
cout << find(n, k);
return 0;
}
|
Java
class Test
{
private int josephus( int n, int k)
{
int sum = 0 ;
for ( int i = 2 ; i <= n; i++)
{
sum = (sum + k) % i;
}
return sum+ 1 ;
}
public static void main(String[] args)
{
int n = 14 ;
int k = 2 ;
Test obj = new Test();
System.out.println(obj.josephus(n, k));
}
}
|
Python3
def find(n, k):
sum = 0
for i in range ( 2 ,n + 1 ):
sum = ( sum + k) % i
return sum + 1
n,k = 14 , 2
print (find(n, k))
|
C#
using System;
class Test
{
private int josephus( int n, int k)
{
int sum = 0;
for ( int i = 2; i <= n; i++)
{
sum = (sum + k) % i;
}
return sum+1;
}
public static void Main(String[] args)
{
int n = 14;
int k = 2;
Test obj = new Test();
Console.WriteLine(obj.josephus(n, k));
}
}
|
Javascript
<script>
function find(n, k)
{
let sum = 0, i;
for (i = 2; i <= n; i++)
sum = (sum + k) % i;
return sum + 1;
}
let n = 14, k = 2;
document.write(find(n, k), "</br>" );
</script>
|
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.)
C++
#include <bits/stdc++.h>
using namespace std;
long long int find( long long int n, long long int k)
{
deque< long long int > dq;
for ( long long int i = 1; i <= n; i++)
dq.push_back(i);
long long int count = 0;
while (dq.size() > 1) {
long long int curr = dq.front();
dq.pop_front();
count++;
if (count % k == 0)
continue ;
dq.push_back(curr);
}
return dq.back();
}
int main()
{
int n = 14, k = 2;
cout << find(n, k);
return 0;
}
|
Java
import java.util.Deque;
import java.util.LinkedList;
public class Test {
public static int find( int n, int k) {
Deque<Integer> dq = new LinkedList<Integer>();
for ( int i = 1 ; i < n+ 1 ; i++) {
dq.add(i);
}
int count = 0 ;
while (dq.size() > 1 ) {
int curr = dq.peek();
dq.removeFirst();
count++;
if (count % k == 0 ) {
continue ;
}
dq.add(curr);
}
return dq.peekLast();
}
public static void main(String[] args) {
int n = 14 ;
int k = 2 ;
System.out.println(find(n, k));
}
}
|
Python3
from collections import deque
def find(n, k):
dq = deque()
for i in range ( 1 , n + 1 ):
dq.append(i)
count = 0
while len (dq) > 1 :
curr = dq[ 0 ]
dq.popleft()
count + = 1
if count % k = = 0 :
continue
dq.append(curr)
return dq[ - 1 ]
if __name__ = = '__main__' :
n = 14
k = 2
print (find(n, k))
|
C#
using System;
using System.Collections.Generic;
class Test {
public static int Find( int n, int k) {
Queue< int > dq = new Queue< int >();
for ( int i = 1; i < n + 1; i++) {
dq.Enqueue(i);
}
int count = 0;
while (dq.Count > 1) {
int curr = dq.Peek();
dq.Dequeue();
count++;
if (count % k == 0) {
continue ;
}
dq.Enqueue(curr);
}
return dq.Peek();
}
static void Main( string [] args) {
int n = 14;
int k = 2;
Console.WriteLine(Find(n, k));
}
}
|
Javascript
function find(n, k) {
const dq = [];
for (let i = 1; i <= n; i++) {
dq.push(i);
}
let count = 0;
while (dq.length > 1)
{
const curr = dq.shift();
count++;
if (count % k === 0) {
continue ;
}
dq.push(curr);
}
return dq[0];
}
const n = 14, k = 2;
console.log(find(n, k));
|
Time Complexity : O(N)
Auxiliary Space : O(N), for pushing the N elements in the queue.
Last Updated :
20 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...