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++
#include <iostream>
using namespace std;
#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>
void orderOfExecution( int N, int K)
{
ordered_set V;
for ( int i = 1; i <= N; ++i)
V.insert(i);
int pos = 0;
while (V.size() > 1) {
pos = (pos + K) % ( int )V.size();
cout << *(V.find_by_order(pos)) << ' ' ;
V.erase(*(V.find_by_order(pos)));
pos %= ( int )V.size();
}
cout << *(V.find_by_order(0));
}
int main()
{
int N = 5, K = 2;
orderOfExecution(N, K);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.TreeSet;
class Main {
static void orderOfExecution( int N, int K)
{
TreeSet<Integer> V = new TreeSet<>();
for ( int i = 1 ; i <= N; ++i)
V.add(i);
int pos = 0 ;
while (V.size() > 1 ) {
pos = (pos + K) % V.size();
System.out.print(V.toArray()[pos] + " " );
V.remove(V.toArray()[pos]);
pos %= V.size();
}
System.out.print(V.toArray()[ 0 ]);
}
public static void main(String[] args)
{
int N = 5 , K = 2 ;
orderOfExecution(N, K);
}
}
|
Python3
def orderOfExecution(N, K):
s = set ( range ( 1 , N + 1 ))
pos = 0
while len (s) > 1 :
pos = (pos + K) % len (s)
element = list (s)[pos]
print (element, end = " " )
s.remove(element)
pos % = len (s)
print (s.pop())
if __name__ = = '__main__' :
N = 5
K = 2
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)
{
int N = 5, K = 2;
OrderOfExecution(N, K);
}
static void OrderOfExecution( int N, int K)
{
SortedSet< int > V = new SortedSet< int >();
for ( int i = 1; i <= N; ++i)
V.Add(i);
int pos = 0;
while (V.Count > 1)
{
pos = (pos + K) % V.Count;
Console.Write(V.ElementAt(pos) + " " );
V.Remove(V.ElementAt(pos));
pos %= V.Count;
}
Console.Write(V.ElementAt(0));
}
}
}
|
Javascript
function orderOfExecution(N, K) {
const numbers = Array.from({ length: N }, (_, i) => i + 1);
let pos = 0;
while (numbers.length > 1) {
pos = (pos + K - 1) % numbers.length;
process.stdout.write(numbers.splice(pos, 1)[0] + ' ' );
pos %= numbers.length;
}
console.log(numbers[0]);
}
const N = 5;
const K = 3;
orderOfExecution(N, K);
|
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Last Updated :
15 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...