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.
Note: The last child is considered dead at the end by default.
Examples:
Input: N = 5, K = 2
Output: 3 1 5 2 4
Explanation:
Initially, the arrangement is {1, 2, 3, 4, 5} and the operations performed are:
- Counting from 1, the Kth child is 3. So the 3rd child gets killed. After that, the children left to be executed are {1, 2, 4, 5}, and then execution of child 4 begins.
- Counting from 4, the Kth child is 1. So the first child gets killed. After that, the children left to be executed are {2, 4, 5}, and then execution of child 2 begins.
- Counting from 2, the Kth child is 5. So the fifth child gets killed. After that, the children left to be executed are {2, 4}, and then execution of child 2 begins.
- Counting from 2, the Kth child is 2. So the second child gets killed. After that, the child left to be executed is 2, and then execution of child 4 begins.
- Finally, child 4 is the only remaining child. So the child will be killed.
Input: N = 7, K = 2
Output: 3 6 2 7 5 1 4
Naive Approach: The simplest idea is to use a vector to store the position of the remaining children. Then iterate while the size of the vector is greater than 1, and in each iteration erase the desired position from the vector.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized using an ordered set. Follow the steps below to solve the problem:
- Initialize an ordered set, say V, and insert the elements in the range [1, N] into V.
- Initialize a variable, say pos as 0, to store the index of the removed element.
- Iterate until the size of the set, V is greater than 1, and perform the following steps:
- Store the size of the set in a variable, say X.
- Update the value of pos to (pos + K) % X.
- Print the element pointed by pos in V and then erase it.
- Update pos to pos%V.size().
- Finally, after completing the above steps, print the last element stored at the beginning of set V.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <iostream> using namespace std; // Header files, namespaces to use // ordered set #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set \ tree< int , null_type, less< int >, rb_tree_tag, \ tree_order_statistics_node_update> // Function to find the child who // will get killed in the ith step void orderOfExecution( int N, int K) { // Create an ordered set ordered_set V; // Push elements in the range // [1, N] in the set for ( int i = 1; i <= N; ++i) V.insert(i); // Stores the position to be removed int pos = 0; // Iterate until the size of the set // is greater than 1 while (V.size() > 1) { // Update the position pos = (pos + K) % ( int )V.size(); // Print the removed element cout << *(V.find_by_order(pos)) << ' ' ; // Erase it from the ordered set V.erase(*(V.find_by_order(pos))); // Update position pos %= ( int )V.size(); } // Print the first element of the set cout << *(V.find_by_order(0)); } // Driver Code int main() { // Given input int N = 5, K = 2; // Function Call orderOfExecution(N, K); return 0; } |
Java
import java.io.*; import java.lang.*; import java.util.*; import java.util.TreeSet; class Main { // Function to find the child who // will get killed in the ith step static void orderOfExecution( int N, int K) { // Create an ordered set TreeSet<Integer> V = new TreeSet<>(); // Push elements in the range // [1, N] in the set for ( int i = 1 ; i <= N; ++i) V.add(i); // Stores the position to be removed int pos = 0 ; // Iterate until the size of the set // is greater than 1 while (V.size() > 1 ) { // Update the position pos = (pos + K) % V.size(); // Print the removed element System.out.print(V.toArray()[pos] + " " ); // Erase it from the ordered set V.remove(V.toArray()[pos]); // Update position pos %= V.size(); } // Print the first element of the set System.out.print(V.toArray()[ 0 ]); } // Driver Code public static void main(String[] args) { // Given input int N = 5 , K = 2 ; // Function Call orderOfExecution(N, K); } } |
Python3
def orderOfExecution(N, K): # Create a set of integers from 1 to N s = set ( range ( 1 , N + 1 )) # Stores the position to be removed pos = 0 # Iterate until the size of the set # is greater than 1 while len (s) > 1 : # Update the position pos = (pos + K) % len (s) # Get the element at pos element = list (s)[pos] # Print the removed element print (element, end = " " ) # Erase it from the set s.remove(element) # Update position pos % = len (s) # Print the first element of the set print (s.pop()) # Driver Code if __name__ = = '__main__' : # Given input N = 5 K = 2 # Function Call orderOfExecution(N, K) |
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApp { class Program { static void Main( string [] args) { // Given input int N = 5, K = 2; // Function Call OrderOfExecution(N, K); } // Function to find the child who // will get killed in the ith step static void OrderOfExecution( int N, int K) { // Create an ordered set SortedSet< int > V = new SortedSet< int >(); // Push elements in the range // [1, N] in the set for ( int i = 1; i <= N; ++i) V.Add(i); // Stores the position to be removed int pos = 0; // Iterate until the size of the set // is greater than 1 while (V.Count > 1) { // Update the position pos = (pos + K) % V.Count; // Print the removed element Console.Write(V.ElementAt(pos) + " " ); // Erase it from the ordered set V.Remove(V.ElementAt(pos)); // Update position pos %= V.Count; } // Print the first element of the set Console.Write(V.ElementAt(0)); } } } // This code is contributed by divyansh2212 |
Javascript
function orderOfExecution(N, K) { // Create an array of numbers from 1 to N const numbers = Array.from({ length: N }, (_, i) => i + 1); // Stores the position to be removed let pos = 0; // Iterate until the size of the array // is greater than 1 while (numbers.length > 1) { // Update the position pos = (pos + K - 1) % numbers.length; // Print the removed element process.stdout.write(numbers.splice(pos, 1)[0] + ' ' ); // Update position pos %= numbers.length; } // Print the first element of the array console.log(numbers[0]); } // Given input const N = 5; const K = 3; // Function Call orderOfExecution(N, K); // This code is contributed by divyansh2212 |
3 1 5 2 4
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)