Skip to content
Related Articles

Related Articles

Josephus problem | Set 1 (A O(n) Solution)
  • Difficulty Level : Hard
  • Last Updated : 15 Apr, 2021
GeeksforGeeks - Summer Carnival Banner

In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem. Following is the problem statement:
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.
For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. 
If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, 1 are killed in order, and person at position 4 survives.

The problem has following recursive structure.  

  josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1
  josephus(1, k) = 1

After the first person (kth from beginning) is killed, n-1 persons are left. So we call 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, we must make adjustments to the position returned by josephus(n – 1, k). 
Following is simple recursive implementation of the Josephus problem. The implementation simply follows the recursive structure mentioned above.  

C++




#include <iostream>
using namespace std;
 
int josephus(int n, int k)
{
    if (n == 1)
        return 1;
    else
        /* The position returned by josephus(n - 1, k)
        is adjusted because the recursive call
        josephus(n - 1, k) considers the
        original position k % n + 1 as position 1 */
        return (josephus(n - 1, k) + k-1) % n + 1;
}
 
// Driver Program to test above function
int main()
{
    int n = 14;
    int k = 2;
    cout << "The chosen place is " << josephus(n, k);
    return 0;
}
 
// This code is contributed by shubhamsingh10

C




#include <stdio.h>
 
int josephus(int n, int k)
{
  if (n == 1)
    return 1;
  else
    /* The position returned by josephus(n - 1, k) is adjusted because the
       recursive call josephus(n - 1, k) considers the original position
       k%n + 1 as position 1 */
    return (josephus(n - 1, k) + k-1) % n + 1;
}
 
// Driver Program to test above function
int main()
{
  int n = 14;
  int k = 2;
  printf("The chosen place is %d", josephus(n, k));
  return 0;
}

Java




// Java code for Josephus Problem
import java.io.*;
 
class GFG {
 
static int josephus(int n, int k)
{
if (n == 1)
    return 1;
else
    /* The position returned by josephus(n - 1, k)
    is adjusted because the recursive call
    josephus(n - 1, k) considers the original
    position k%n + 1 as position 1 */
    return (josephus(n - 1, k) + k-1) % n + 1;
}
 
// Driver Program to test above function
public static void main(String[] args)
{
int n = 14;
int k = 2;
System.out.println("The chosen place is " + josephus(n, k));
}
}
 
// This code is contributed by Prerna Saini

Python3




# Python code for Josephus Problem
 
def josephus(n, k):
 
      if (n == 1):
          return 1
      else:
     
     
          # The position returned by
          # josephus(n - 1, k) is adjusted
          # because the recursive call
          # josephus(n - 1, k) considers
          # the original position
          # k%n + 1 as position 1
          return (josephus(n - 1, k) + k-1) % n + 1
 
# Driver Program to test above function
 
n = 14
k = 2
 
print("The chosen place is ", josephus(n, k))
 
# This code is contributed by
# Sumit Sadhakar

C#




// C# code for Josephus Problem
using System;
 
class GFG {
     
    static int josephus(int n, int k)
    {
        if (n == 1)
            return 1;
        else
            /* The position returned
            by josephus(n - 1, k) is
            adjusted because the
            recursive call josephus(n
            - 1, k) considers the
            original position k%n + 1
            as position 1 */
            return (josephus(n - 1, k)
                       + k-1) % n + 1;
    }
     
    // Driver Program to test above
    // function
    public static void Main()
    {
        int n = 14;
        int k = 2;
        Console.WriteLine("The chosen "
        + "place is " + josephus(n, k));
    }
}
 
// This code is contributed by anuj_67.

PHP




<?php
// PHP code for
// Josephus Problem
 
function josephus($n, $k)
{
    if ($n == 1)
        return 1;
    else
        /* The position returned by
           josephus(n - 1, k) is
           adjusted because the
           recursive call josephus
           (n - 1, k) considers the
           original position k%n + 1
           as position 1 */
        return (josephus($n - 1, $k) +
                    $k - 1) % $n + 1;
}
 
    // Driver Code
    $n = 14;
    $k = 2;
    echo "The chosen place is ", josephus($n, $k);
 
// This code is contributed by ajit.
?>

Javascript




<script>
 
    // Javascript code for Josephus Problem
     
    function josephus(n, k)
    {
        if (n == 1)
            return 1;
        else
            /* The position returned
            by josephus(n - 1, k) is
            adjusted because the
            recursive call josephus(n
            - 1, k) considers the
            original position k%n + 1
            as position 1 */
            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)



Another Approach using List:

The simple approach is to create a list and add all values from 1 to n in it. Create a recursive function which takes list , start (position at which counting will start) and k ( number of person to be skipped) as argument. If size of list is one i.e. only one person left then return this position. Otherwise start counting k person in clockwise direction from starting position and remove the person at kth position. Now the person at kth position is removed and now counting will start from this position. This process continues till only one person left.

pseudo-code :

Josephus( list , start , k){
   if list.size = 1
       return list[0]
   start = (start + k) % list.size
   list.remove( start )
   return Josephus( list, start, k)
}

Example :

Input : n = 5,  k = 2
output : 3

Explanation :

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 list. The new counting will begins from 1-index, 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 person, counting start 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) killed so now we have 3 person left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here.

The person at 0-index 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 person at 1-index killed and only person who is left is at position 3.

Similarly, If n = 40 and k =7 then the person at position 24 will be safe.

Let’s see the code : 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Recursive function
int josephus(vector<int> list, int start, int k)
{
  // If size of list is one
  // then return its value
  if(list.size() == 1)
  {
    return list[0];
  }
 
  // Counting kth person and
  // check so that it don't go out of bound
  start = (start + k) % list.size();
 
  // Removing the kth person
  list.erase(list.begin() + start);
 
  // Calling recursive function again until only one
  // person left Start is now the position of previous
  // person who is killed Ex. if person at 1-index
  // killed then person at 2-index shifted to 1-index
  // and counting start from here
  return josephus(list, start, k);
}
 
// Driver code
int main()
{
 
  // Number of people to be executed
  // Number of people to be skipped
  int n = 7, k = 3;
 
  // Initialising an vctorList
  vector<int> list;
 
  // Calling function with starting position at
  // 0-index and k-1 so that kth person will be killed
  // Storing the safe position
  for(int i = 1; i <= n; i++)
  {
    list.push_back(i);
  }
 
  // Printing the ressult.
  cout << josephus(list, 0, k - 1) << endl;
  return 0;
}
 
// This code is contributed by sk1122.

Java




// Java program for Josephus problem
import java.util.*;
 
// Main class
public class GFG {
 
    // Recursive function
    public static int josephus(ArrayList<Integer> list,
                               int start, int k)
    {
 
        // If size of list is one
        // then return its value
        if (list.size() == 1) {
            return list.get(0);
        }
 
        // Counting kth person and
        // check so that it don't go out of bound
        start = (start + k) % list.size();
 
        // Removing the kth person
        list.remove(start);
 
        // Calling recursive function again until only one
        // person left Start is now the position of previous
        // person who is killed Ex. if person at 1-index
        // killed then person at 2-index shifted to 1-index
        // and counting start from here
        return josephus(list, start, k);
    }
 
    // Main function
    public static void main(String[] args)
    {
 
        // Number of people to be executed
        int n = 7;
 
        // Number of person to be skipped
        int k = 3;
 
        // Initialising an ArrayList
        ArrayList<Integer> list = new ArrayList<>();
 
        // Storing value from 1 to n
        for (int i = 1; i <= n; i++) {
            list.add(i);
        }
 
        // Calling function with starting position at
        // 0-index and k-1 so that kth person will be killed
        // Storing the safe position
        int safePosition = josephus(list, 0, k - 1);
 
        // Printing the result
        System.out.println("The safe position : "
                           + safePosition);
    }
}
Output
The safe position : 4
 

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 you want to share more information about the topic discussed above. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :