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 of the last alive person.
Examples:
Input: N = 5, K = 2
Output: 3
Explanation:Â
One way to perform the operations is:
- Step 1: Initially, the counting starts from position 1. Therefore, the Kth alive person at position 2 is killed, so the remaining alive persons are at positions {1, 3, 4, 5}.
- Step 2: Now, the counting starts from position 3. Therefore, the Kth alive person at position 4 is killed, so the remaining alive persons are at positions {1, 3, 5}.
- Step 3: Now, the counting starts from position 5. Therefore, the Kth alive person at position 1 is killed, so the remaining alive persons are at positions {3, 5}.
- Step 4: Now, the counting starts from position 3. Therefore, the Kth alive person at position 5 is killed, so the last alive person is at position 3.
Therefore, the last remaining person living is at position 3.
Input: N = 10, K = 4
Output: 5
Different approaches to solve this problem are discussed in Set 1 and Set 2 of this article.
Approach 1(Using Vector): The above-given problem is known as Josephus’s problem. The problem can be solved using recursion and vector data structure from the STL library. Follow the steps below to solve the problem:Â
- Initialize a vector say, arr[] to store the positions of all the persons.
- Iterate in the range [1, N] using the variable i and in each iteration append i to the vector arr[].
- Define a recursive function say RecursiveJosephus(vector<int>:: iterator it, vector<int>arr), where it points to the current alive person from where K elements are to be counted.
- If the size of the vector, arr is 1, then return the value in arr[0].
- Iterate in the range [1, K-1] and then, in each iteration, increment it by 1 and if it becomes equal, arr. end() then assign arr.begin() to it.
- Now if it is pointing to the last element of the vector arr, then pop the last element of the vector, arr, and then update it with the position of (K+1)th alive person, i.e., arr.begin().
- Otherwise, erase the position of the person pointed by it. After deletion, it now points to the position of the (K+1)th person.
- Finally, after completing the above steps, call the function RecursiveJosephus(arr.begin(), arr) and print the value returned by it as the position of the last alive person.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Recursive auxiliary function to find// the position of thevlast alive personint RecursiveJosephus(vector<int>& arr, int K,                      vector<int>::iterator it){    // If size of arr is 1    if (arr.size() == 1) {        return arr[0];    }Â
    // Iterate over the range [1, K-1]    for (int i = 1; i < K; i++) {Â
        // Increment it by 1        it++;Â
        // If it is equal to arr.end()        if (it == arr.end()) {Â
            // Assign arr.begin() to it            it = arr.begin();        }    }Â
    // If it is equal to prev(arr.end())    if (it == prev(arr.end())) {Â
        // Assign arr.begin() to it        it = arr.begin();Â
        // Remove the last element        arr.pop_back();    }    else {Â
        // Erase the element at it        arr.erase(it);    }Â
    // Return the last alive person    return RecursiveJosephus(arr, K, it);}Â
// Function to find the position of the// last alive personint Josephus(int N, int K){    // Stores positions of every person    vector<int> arr;    for (int i = 1; i <= N; i++)        arr.push_back(i);Â
    // Function call to find the position    // of the last alive person    return RecursiveJosephus(arr, K, arr.begin());}Â
// Driver Codeint main(){    // Given Input    int N = 5;    int K = 2;Â
    // Function Call    cout << Josephus(N, K);} |
Java
import java.util.List;import java.util.ArrayList;Â
public class Main {Â
  // Recursive auxiliary function to find  // the position of the last alive person  public static int recursiveJosephus(List<Integer> arr, int K, int it) {Â
    // If size of arr is 1    if (arr.size() == 1) {      return arr.get(0);    }         // Iterate over the range [1, K-1]    for (int i = 1; i < K; i++) {             // Increment it by 1      it++;      if (it == arr.size()) {        it = 0;      }    }    if (it == arr.size() - 1) {      // Remove the eliminated person from the list      it = 0;      arr.remove(arr.size() - 1);    } else {      arr.remove(it);    }    // Recursively call the function with the new list of people    return recursiveJosephus(arr, K, it);  }Â
  // Function to find the position of the last alive person  public static int josephus(int N, int K) {         // Create a list of people    List<Integer> arr = new ArrayList<Integer>();    for (int i = 1; i <= N; i++) {      arr.add(i);    }         // Call the recursive function to find the position of the last alive person    return recursiveJosephus(arr, K, 0);  }Â
  // Driver code  public static void main(String[] args) {    int N = 5;    int K = 2;    System.out.println(josephus(N, K));  }} |
Python3
# Python program for the above approachfrom typing import List# Recursive auxiliary function to find# the position of thevlast alive persondef RecursiveJosephus(arr: List[int], K: int, it: int):Â Â Â Â Â Â #If size of arr is 1Â
    if len(arr) == 1:        return arr[0] #Iterate over the range [1, K-1]Â
    for i in range(1, K):       # Increment it by 1Â
        it += 1        if it == len(arr):            it = 0    if it == len(arr) - 1: # Remove the eliminated person from the listÂ
        it = 0        arr.pop()    else:        arr.pop(it)        # Recursively call the function with the new list of peopleÂ
    return RecursiveJosephus(arr, K, it)#Function to find the position of the last alive persondef Josephus(N: int, K: int):  # Create a list of peopleÂ
    arr = list(range(1, N+1))    # Call the recursive function to find the position of the last alive personÂ
    return RecursiveJosephus(arr, K, 0)#Driver codeÂ
if __name__ == '__main__':Â Â Â Â N = 5Â Â Â Â K = 2Â Â Â Â print(Josephus(N, K)) |
C#
using System;using System.Collections.Generic;Â
public class MainClass{  // Recursive auxiliary function to find  // the position of the last alive person  public static int RecursiveJosephus(List<int> arr, int K, int it)  {    // If size of arr is 1    if (arr.Count == 1)    {      return arr[0];    }Â
    // Iterate over the range [1, K-1]    for (int i = 1; i < K; i++)    {      // Increment it by 1      it++;      if (it == arr.Count)      {        it = 0;      }    }Â
    if (it == arr.Count - 1)    {      // Remove the eliminated person from the list      it = 0;      arr.RemoveAt(arr.Count - 1);    }    else    {      arr.RemoveAt(it);    }Â
    // Recursively call the function with the new list of people    return RecursiveJosephus(arr, K, it);  }Â
  // Function to find the position of the last alive person  public static int Josephus(int N, int K)  {    // Create a list of people    List<int> arr = new List<int>();    for (int i = 1; i <= N; i++)    {      arr.Add(i);    }Â
    // Call the recursive function to find the position of the last alive person    return RecursiveJosephus(arr, K, 0);  }Â
  // Driver code  public static void Main()  {    int N = 5;    int K = 2;    Console.WriteLine(Josephus(N, K));  }} |
Javascript
// JavaScript code//Recursive auxiliary function to find// the position of thevlast alive personfunction recursiveJosephus(arr, K, it) {  //If size of arr is 1  if (arr.length === 1) {    return arr[0];  }  //Iterate over the range [1, K-1]  for (let i = 1; i < K; i++) {    // Increment it by 1    it += 1;    if (it == arr.length) {      it = 0;    }  }  if (it == arr.length - 1) { // Remove the eliminated person from the list    it = 0;    arr.pop();  } else {    arr.splice(it, 1);    // Recursively call the function with the new list of people  }  return recursiveJosephus(arr, K, it);}//Function to find the position of the last alive personfunction josephus(N, K) {  // Create a list of people  let arr = [];  for (let i = 1; i <= N; i++) {    arr.push(i);  }  // Call the recursive function to find the position of the last alive person  return recursiveJosephus(arr, K, 0);}//Driver code  const N = 5;  const K = 2;  console.log(josephus(N, K)); |
3
Time Complexity: O(N2)
Auxiliary Space: O(N)
Approach 2(Using SET): The problem can be solved using recursion and a set data structure from the STL library. Follow the steps below to solve the problem:Â
- Initialize a set say, arr to store the positions of all the persons.
- Iterate in the range [1, N] using the variable i, and in each iteration insert i in the set arr.
- Define a recursive function say RecursiveJosephus(set<int>:: iterator it, set<int>arr), where it points to the position of the current alive person from where K elements are to be counted.
- If the size of the set arr is 1, then return the value pointed by the iterator, it.
- Iterate in the range [1, K-1] and then, in each iteration, increment it by 1 and if it becomes equal to arr. end(), then assign arr.begin() to it.
- Now if it is pointing to the position of the last element of the set, arr, then delete the last element of the set, arr, and then update it with the position of the (K+1)th, person i.e arr.begin().
- Otherwise, store the value of the next iterator of it in a variable, say val then erase the position pointed by it.
- After deletion, it becomes invalid. Therefore, now find the value of val in the set, arr, and then assign it to it. Now it points to the position of the (K+1)th living person.
- Finally, after completing the above steps, call the function RecursiveJosephus(arr.begin(), arr) and print the value returned by it as the position of the last living person.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Recursive auxiliary function to find// the position of the last alive personint RecursiveJosephus(set<int>& arr, int K,                      set<int>::iterator it){Â
    // If size of arr is 1    if (arr.size() == 1) {        return *it;    }Â
    // Iterate over the range [1, K-1]    for (int i = 1; i < K; i++) {Â
        // Increment it by 1        it++;Â
        // If it is equal to arr.end()        if (it == arr.end()) {Â
            // Assign arr.begin() to it            it = arr.begin();        }    }Â
    // If it is equal to prev(arr.end())    if (it == prev(arr.end())) {Â
        // Assign arr.begin() to it        it = arr.begin();Â
        // Remove the last element        arr.erase(prev(arr.end()));    }    else {Â
        // Stores the value pointed        // by next iterator of it        int val = (*next(it));Â
        // Erase the element at it        arr.erase(it);Â
        // Update it        it = arr.find(val);    }Â
    // Return the position of    // the last alive person    return RecursiveJosephus(arr, K, it);}Â
// Function to find the position// of the last alive personint Josephus(int N, int K){    // Stores all the persons    set<int> arr;Â
    for (int i = 1; i <= N; i++)        arr.insert(i);Â
    // Function call to find the position    // of the last alive person    return RecursiveJosephus(arr, K, arr.begin());}Â
// Driver Codeint main(){    // Given Input    int N = 5;    int K = 2;Â
    // Function Call    cout << Josephus(N, K);} |
3
Time Complexity: O(N*K+N*log(N))
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



