Skip to content
Related Articles

Related Articles

Improve Article

Josephus Problem | Set 3 (using STL)

  • Last Updated : 06 Jul, 2021

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:

  1. 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}.
  2. 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}.
  3. 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}.
  4. 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.
  • 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
// vthe position of thevlast alive person
int 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 person
int 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 Code
int main()
{
    // Given Input
    int N = 5;
    int K = 2;
  
    // Function Call
    cout << Josephus(N, K);
}
Output
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 person
int 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 person
int 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 Code
int main()
{
    // Given Input
    int N = 5;
    int K = 2;
  
    // Function Call
    cout << Josephus(N, K);
}
Output
3

Time Complexity: O(N*K+N*log(N))
Auxiliary Space: O(N)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :