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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!