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 the kth person is killed in a circle. The task is to choose the person in the initial circle that survives.
Examples:
Input: N = 5 and k = 2
Output: 3
Explanation: Firstly, the person at position 2 is killed,
then the person at position 4 is killed, then the person at position 1 is killed.
Finally, the person at position 5 is killed. So the person at position 3 survives.
Input: N = 7 and k = 3
Output: 4
Explanations: The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order,
and the person at position 4 survives.
Josephus problem using List:
The simple approach is to create a list and add all values from 1 to N to it. Create a recursive function that takes a list, start (position at which counting will start), and k ( number of people to be skipped) as an argument. If the size of the list is one i.e. only one person left then return this position. Otherwise, start counting the k person in a clockwise direction from starting position and remove the person at the kth position. Now the person at the kth position is removed and now counting will start from this position. This process continues till only one person is left.
Pseudocode :
Josephus( list , start , k){
if list.size = 1
return list[0]
start = (start + k) % list.size
list.remove( start )
return Josephus( list, start, k)
}
Follow the below steps to Implement the idea:
- Create a vector person and push all the values from 1 to N in person.
- Recursively eliminate the index element
- Erase the element on the position index.
- Call for (index + k)% size of person.
- If size of person = 1, return person[i].
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void Josh(vector< int > person, int k, int index)
{
if (person.size() == 1) {
cout << person[0] << endl;
return ;
}
index = ((index + k) % person.size());
person.erase(person.begin() + index);
Josh(person, k, index);
}
int main()
{
int n = 14;
int k = 2;
k--;
int index
= 0;
vector< int > person;
for ( int i = 1; i <= n; i++) {
person.push_back(i);
}
Josh(person, k, index);
}
|
Java
import java.util.*;
class GFG{
static void Josh(List<Integer> person, int k, int index)
{
if (person.size() == 1 ) {
System.out.println(person.get( 0 ));
return ;
}
index = ((index + k) % person.size());
person.remove(index);
Josh(person, k, index);
}
public static void main(String [] args)
{
int n = 14 ;
int k = 2 ;
k--;
int index
= 0 ;
List<Integer> person = new ArrayList<>();
for ( int i = 1 ; i <= n; i++) {
person.add(i);
}
Josh(person, k, index);
}
}
|
Python3
def Josh(person, k, index):
if len (person) = = 1 :
print (person[ 0 ])
return
index = ((index + k) % len (person))
person.pop(index)
Josh(person,k,index)
n = 14
k = 2
k - = 1
index = 0
person = []
for i in range ( 1 ,n + 1 ):
person.append(i)
Josh(person,k,index)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void Josh(List< int > person, int k, int index)
{
if (person.Count == 1) {
Console.WriteLine(person[0]);
return ;
}
index = ((index + k) % person.Count);
person.RemoveAt(index);
Josh(person, k, index);
}
static void Main()
{
int n = 14;
int k = 2;
k--;
int index
= 0;
List< int > person = new List< int >();
for ( int i = 1; i <= n; i++) {
person.Add(i);
}
Josh(person, k, index);
}
}
|
Javascript
<script>
function Josh( person , k , index) {
if (person.length == 1) {
document.write(person[0]);
return ;
}
index = ((index + k) % person.length);
if (index > -1) {
person.splice(index, 1);
}
Josh(person, k, index);
}
var n = 14;
var k = 2;
k--;
var index = 0;
var person = [];
for ( var i = 1; i <= n; i++) {
person.push(i);
}
Josh(person, k, index);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N), For recursion stack
Approach to solve Josephus problem iteratively:
Illustration:
N = 5, k = 2
Add all values from 1 to N in the list. We will call the recursive function with start = 0 and k = 1 (0-indexing)

Now the element at 1-index (person number 2) will be killed. And it is removed from the list. The new counting will begin from 1-index, the person at 1-index killed so now person at 2-index (person number 3) comes to 1-index and counting starts from here now.

Now we have 4 people, counting starting from 1-index (person number 3) and the person at kth (2-index ) position will be killed.

The person at 2-index (person number 4) was killed so now we have 3 people left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here.

The person at the 0-index was killed and we have now two-person left in the circle. And the person at 1-index shifted to 0-index i.e. person number 3.

Final counting done and the person at 1-index killed and the only person who is left is at position 3.

Follow the below steps to Implement the idea:
- Initialize variables num, cnt, and cut with 1, 0, and 0 respectively and an array arr[] of size N with the initial value set as 1.
- Run a while loop till cnt < N:
- Run a while loop till num is less than equal to k.
- Increment cut by one and take modulo by N
- If arr[cut] = 1 increment num by one.
- Set num = 1, arr[cut] = 0 and increment cnt and cut by one and cut = cut % n;
- Run a while loop till arr[cut] = 0 and increment cut by one.
- Return cnt + 1 as the required answer.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int Josephus( int , int );
int Josephus( int n, int k)
{
k--;
int arr[n];
for ( int i = 0; i < n; i++) {
arr[i] = 1;
}
int cnt = 0, cut = 0,
num = 1;
while (cnt < (n - 1)) {
while (num <= k) {
cut++;
cut = cut % n;
if (arr[cut] == 1) {
num++;
}
}
num = 1;
arr[cut] = 0;
cnt++;
cut++;
cut = cut % n;
while (arr[cut] == 0) {
cut++;
cut = cut % n;
}
}
return cut + 1;
}
int main()
{
int n = 14, k = 2;
cout << Josephus(n, k);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int n = 14 , k = 2 ;
System.out.println(Josephus(n, k));
}
public static int Josephus( int n, int k)
{
k--;
int arr[] = new int [n];
for ( int i = 0 ; i < n; i++) {
arr[i] = 1 ;
}
int cnt = 0 , cut = 0 ,
num
= 1 ;
while (
cnt
< (n
- 1 ))
{
while (num
<= k)
{
cut++;
cut = cut
% n;
if (arr[cut] == 1 ) {
num++;
}
}
num = 1 ;
arr[cut] = 0 ;
cnt++;
cut++;
cut = cut % n;
while (arr[cut]
== 0 )
{
cut++;
cut = cut
% n;
}
}
return cut
+ 1 ;
}
}
|
Python3
def Josephus(n, k):
k - = 1
arr = [ 0 ] * n
for i in range (n):
arr[i] = 1
cnt = 0
cut = 0
num = 1
while (cnt < (n - 1 )):
while (num < = k):
cut + = 1
cut = cut % n
if (arr[cut] = = 1 ):
num + = 1
num = 1
arr[cut] = 0
cnt + = 1
cut + = 1
cut = cut % n
while (arr[cut] = = 0 ):
cut + = 1
cut = cut % n
return cut + 1
n, k = 14 , 2
print (Josephus(n, k))
|
C#
using System;
using System.Linq;
public class GFG{
public static void Main ()
{
int n = 14, k = 2;
Console.Write(Josephus(n, k));
}
public static int Josephus( int n, int k)
{
k--;
int [] arr = new int [n];
for ( int i = 0; i < n; i++) {
arr[i] = 1;
}
int cnt = 0, cut = 0,
num = 1;
while (
cnt
< (n - 1))
{
while (num <= k)
{
cut++;
cut = cut % n;
if (arr[cut] == 1)
{
num++;
}
}
num = 1;
arr[cut]
= 0;
cnt++;
cut++;
cut = cut
% n;
while (arr[cut]
== 0)
{
cut++;
cut = cut % n;
}
}
return cut + 1;
}
}
|
Javascript
<script>
let n = 14, k = 2;
document.write(Josephus(n, k));
function Josephus(n, k)
{
k--;
let arr = new Array(n);
for (let i = 0; i < n; i++)
{
arr[i] = 1;
}
let cnt = 0, cut = 0,
num = 1;
while (cnt < (n - 1))
{
while (num <= k)
{
cut++;
cut = cut % n;
if (arr[cut] == 1)
{
num++;
}
}
num = 1;
arr[cut] = 0;
cnt++;
cut++;
cut = cut % n;
while (arr[cut] == 0)
{
cut++;
cut = cut % n;
}
}
return cut + 1;
}
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Josephus Problem in Linear Time and Constant Space:
Follow the below steps to Solve the Problem (Approach):
- Initialize variables i and ans with 1 and 0 respectively.
- Run a while loop till i <= N:
- Update ans with (ans + k) % i.
- Increment i by 1.
- Return ans + 1 as the required answer.
Below is the Implementation of the above Steps:
C++
#include <iostream>
using namespace std;
int Josephus( int N, int k)
{
int i = 1, ans = 0;
while (i <= N) {
ans = (ans + k) % i;
i++;
}
return ans + 1;
}
int main()
{
int N = 14, k = 2;
cout << Josephus(N, k) << endl;
return 0;
}
|
C
#include <stdio.h>
int Josephus( int N, int k)
{
int i = 1, ans = 0;
while (i <= N) {
ans = (ans + k) % i;
i++;
}
return ans + 1;
}
int main()
{
int N = 14, k = 2;
printf ( "%d" , Josephus(N, k));
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int Josephus( int N, int k) {
int i = 1 , ans = 0 ;
while (i <= N) {
ans = (ans + k) % i;
i++;
}
return ans + 1 ;
}
public static void main (String[] args) {
int N = 14 , k = 2 ;
int ans = Josephus(N, k);
System.out.println(ans);
}
}
|
Python
def Josephus(n, k):
i = 1
ans = 0
while (i < = n):
ans = (ans + k) % i
i + = 1
return ans + 1
n = 14
k = 2
result = Josephus(n, k)
print (result)
|
Javascript
let n = 14, k = 2;
document.write(Josephus(n,k));
function Josephus(n, k)
{
let i = 1, ans = 0;
while (i <= n ){
ans = (ans + k) % i;
i++;
}
return ans + 1;
}
|
C#
using System;
class GFG
{
public static int Josephus( int N, int k)
{
int i = 1, ans = 0;
while (i <= N)
{
ans = (ans + k) % i;
i++;
}
return ans + 1;
}
static void Main( string [] args)
{
int N = 14, k = 2;
int ans = Josephus(N, k);
Console.WriteLine(ans);
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Josephus Problem using Recursion:
Below is the idea to solve the problem:
The problem has the following recursive structure. josephus(n, k) = (josephus(n – 1, k) + k-1) % n + 1 and josephus(1, k) = 1
After the first person (kth from the beginning) is killed, n-1 persons are left. Make recursive call for Josephus(n – 1, k) to get the position with n-1 persons. But the position returned by Josephus(n – 1, k) will consider the position starting from k%n + 1. So make adjustments to the position returned by Josephus(n – 1, k).
Below is the Implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
int josephus( int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k - 1) % n + 1;
}
int main()
{
int n = 14;
int k = 2;
cout << "The chosen place is " << josephus(n, k);
return 0;
}
|
C
#include <stdio.h>
int josephus( int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k - 1) % n + 1;
}
int main()
{
int n = 14;
int k = 2;
printf ( "The chosen place is %d" , josephus(n, k));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int josephus( int n, int k)
{
if (n == 1 )
return 1 ;
else
return (josephus(n - 1 , k) + k - 1 ) % n + 1 ;
}
public static void main(String[] args)
{
int n = 14 ;
int k = 2 ;
System.out.println( "The chosen place is "
+ josephus(n, k));
}
}
|
Python3
def josephus(n, k):
if (n = = 1 ):
return 1
else :
return (josephus(n - 1 , k) + k - 1 ) % n + 1
n = 14
k = 2
print ( "The chosen place is " , josephus(n, k))
|
C#
using System;
class GFG {
static int josephus( int n, int k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k) + k - 1) % n + 1;
}
public static void Main()
{
int n = 14;
int k = 2;
Console.WriteLine( "The chosen "
+ "place is " + josephus(n, k));
}
}
|
PHP
<?php
function josephus( $n , $k )
{
if ( $n == 1)
return 1;
else
return (josephus( $n - 1, $k ) +
$k - 1) % $n + 1;
}
$n = 14;
$k = 2;
echo "The chosen place is " , josephus( $n , $k );
?>
|
Javascript
<script>
function josephus(n, k)
{
if (n == 1)
return 1;
else
return (josephus(n - 1, k)
+ k-1) % n + 1;
}
let n = 14;
let k = 2;
document.write( "The chosen " + "place is " + josephus(n, k));
</script>
|
Output
The chosen place is 13
Time Complexity: O(N)
Auxiliary Space: O(N) the space used in recursion call stack
Please visit set-2: Josephus problem | Set 2 (A Simple Solution when k = 2)
Source:
http://en.wikipedia.org/wiki/Josephus_problem
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Josephus Problem using Queue :
Approach:
I am using queue data structure, so that i can move the items from one end to another linearly.
we have given ‘K’ the moves we can shift, so after shifting K-1 items to the end of the queue, I am deleting the front element.
On repeating the above step, a stage will come when only one element will be left, this is answer itself.
C++
#include <iostream>
#include <queue> // include the queue library
using namespace std;
int findTheWinner( int n, int k) {
queue< int > q;
int i=1;
while (i<=n){
q.push(i);
i++;
}
while (q.size()!=1){
int j=1;
while (j<k){
int temp=q.front();
q.push(temp);
q.pop();
j++;
}
q.pop();
}
return q.front();
}
int main() {
int n=4, k=2;
int ans = findTheWinner(n,k);
cout << "The winner is player " << ans << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static int findTheWinner( int n, int k)
{
Queue<Integer> q
= new LinkedList<>();
int i = 1 ;
while (i <= n) {
q.add(i);
i++;
}
while (q.size() != 1 ) {
int j = 1 ;
while (j < k) {
int temp = q.peek();
q.add(temp);
q.remove();
j++;
}
q.remove();
}
return q.peek();
}
public static void main(String[] args)
{
int n = 4 , k
= 2 ;
int ans = findTheWinner(n, k);
System.out.println( "The winner is player " + ans);
}
}
|
Python3
from queue import Queue
def findTheWinner(n, k):
q = Queue()
for i in range ( 1 , n + 1 ):
q.put(i)
while q.qsize() ! = 1 :
for j in range (k - 1 ):
temp = q.get()
q.put(temp)
q.get()
return q.get()
n = 4
k = 2
ans = findTheWinner(n, k)
print ( "The winner is player" , ans)
|
C#
using System;
using System.Collections.Generic;
class MainClass {
public static int findTheWinner( int n, int k)
{
Queue< int > q
= new Queue< int >();
int i = 1;
while (i <= n) {
q.Enqueue(i);
i++;
}
while (q.Count != 1) {
int j = 1;
while (j < k) {
int temp = q.Peek();
q.Enqueue(temp);
q.Dequeue();
j++;
}
q.Dequeue();
}
return q.Peek();
}
public static void Main( string [] args)
{
int n = 4, k
= 2;
int ans = findTheWinner(n, k);
Console.WriteLine( "The winner is player " + ans);
}
}
|
Javascript
function findTheWinner(n, k) {
let q = [];
let i = 1;
while (i <= n) {
q.push(i);
i++;
}
while (q.length != 1) {
let j = 1;
while (j < k) {
let temp = q.shift();
q.push(temp);
j++;
}
q.shift();
}
return q[0];
}
let n = 4,
k = 2;
let ans = findTheWinner(n, k);
console.log( "The winner is player " + ans);
|
Output
The winner is player 1
Time Complexity: O(N*K)
Space Complexity: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
06 Jul, 2023
Like Article
Save Article