Open In App

Josephus Problem | (Iterative Solution)

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Java




// 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


Python3




# 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


C#




// 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


Javascript




<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>


Output

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.)

C++




// 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




// 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));
  }
}


Python3




# 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))


C#




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));
  }
}


Javascript




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));


Output

13

Time Complexity : O(N)
Auxiliary Space : O(N), for pushing the N elements in the queue.



Similar Reads

Order of removal in Josephus problem in O(N logN)
Given N children standing in a circle waiting to be executed, and a number K, which indicates that K-1 children are skipped in the clockwise direction, and the Kth child is killed in the circle, and then execution of (K+1)th child begins, the task is to print the child who will get killed in the ith move if the execution starts from the first child
7 min read
Josephus Problem
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 execut
26 min read
Josephus Problem when k is 2
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 execut
12 min read
Josephus Problem Using Bit Magic
The Problem This problem is named after Flavius Josephus a Jewish historian who fought against the Romans. According to Josephus he and his group of Jewish soldiers were cornered &amp; surrounded by the Romans inside a cave, and they choose to murder and suicide inside of surrender and capture. They decided that all the soldiers will sit in a circl
14 min read
CSES Solutions - Josephus Problem II
Consider a game where there are N children (numbered 1,2 ... N) in a circle. During the game, repeatedly K children are skipped and one child is removed from the circle. In which order will the children be removed? Examples: Input: N = 7, K = 2Output: 3 6 2 7 5 1 4Explanation: children = [1, 2, 3, 4, 5, 6, 7], 1 and 2 are skipped and 3 is removed.
11 min read
Josephus Problem | Set 3 (using STL)
Given N persons are standing in a circle and an integer K. If initially starting from the first position, the Kth alive person clockwise from the current position is killed, and then the current position is shifted to the position of (K+1)th alive person and the same step is performed until only one person remains, the task is to print the position
12 min read
CSES Solutions - Josephus Problem I
Consider a game where there are N children (numbered 1,2 ... N) in a circle. During the game, every other child is removed from the circle until there are no children left. In which order will the children be removed? Examples: Input: N = 7Output: 2 4 6 1 5 3 7Explanation: Children = {1, 2, 3, 4, 5, 6, 7}, 1 is skipped and 2 is removed.Children = {
5 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Reverse alternate K nodes in a Singly Linked List - Iterative Solution
Given a linked list and an integer K, the task is to reverse every alternate K nodes.Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; 9 -&gt; NULL, K = 3 Output: 3 2 1 4 5 6 9 8 7Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; 9 -&gt; NULL, K = 5 Output: 5 4 3 2 1 6 7 8 9 Approach: We have alre
12 min read
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See the following examples. The following trees are examples of Complete Binary Trees 1 /
25 min read