The Wayback Machine - https://web.archive.org/web/20241001081346/https://www.geeksforgeeks.org/josephus-problem/
Open In App

Josephus Problem

Last Updated : 12 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
57.26%
1.1L

There are N people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. 

Given the total number of persons N and a number k which indicates that k-1 persons are skipped and the kth person is killed in a circle. The task is to choose the person in the initial circle that survives.

Examples:

Input: N = 5 and k = 2
Output: 3
Explanation: Firstly, the person at position 2 is killed, 
then the person at position 4 is killed, then the person at position 1 is killed. 
Finally, the person at position 5 is killed. So the person at position 3 survives. 

Input: N = 7 and k = 3
Output: 4
Explanations: The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order, 
and the person at position 4 survives.

Josephus problem using List: 

The simple approach is to create a list and add all values from 1 to N to it. Create a recursive function that takes a list, start (position at which counting will start), and k ( number of people to be skipped) as an argument. If the size of the list is one i.e. only one person left then return this position. Otherwise, start counting the k person in a clockwise direction from starting position and remove the person at the kth position. Now the person at the kth position is removed and now counting will start from this position. This process continues till only one person is left.

Pseudocode :

Josephus( list , start , k){
   if list.size = 1
       return list[0]
   start = (start + k) % list.size
   list.remove( start )
   return Josephus( list, start, k)
}

Follow the below steps to Implement the idea:

  • Create a vector person and push all the values from 1 to N in person.
  • Recursively eliminate the index element 
    • Erase the element on the position index.
    • Call for (index + k)% size of person. 
    • If size of person = 1, return person[i].

Below is the Implementation of the above approach:

C++
#include <bits/stdc++.h>

using namespace std;

void Josh(vector<int> person, int k, int index)
{
    // Base case , when only one person is left
    if (person.size() == 1) {
        cout << person[0] << endl;
        return;
    }

    // find the index of first person which will die
    index = ((index + k) % person.size());

    // remove the first person which is going to be killed
    person.erase(person.begin() + index);

    // recursive call for n-1 persons
    Josh(person, k, index);
}

int main()
{
    int n = 14; // specific n and k  values for original
                // josephus problem
    int k = 2;
    k--; // (k-1)th person will be killed
    int index
        = 0; // The index where the person which will die

    vector<int> person;
    // fill the person vector
    for (int i = 1; i <= n; i++) {
        person.push_back(i);
    }

    Josh(person, k, index);
}
Java
import java.util.*;

class GFG{


  static void Josh(List<Integer> person, int k, int index)
  {
    
    // Base case , when only one person is left
    if (person.size() == 1) {
      System.out.println(person.get(0));
      return;
    }

    // find the index of first person which will die
    index = ((index + k) % person.size());

    // remove the first person which is going to be killed
    person.remove(index);

    // recursive call for n-1 persons
    Josh(person, k, index);
  }

  // Driver code
  public static void main(String [] args)
  {
    int n = 14; // specific n and k  values for original
    // josephus problem
    int k = 2;
    k--; // (k-1)th person will be killed
    int index
      = 0; // The index where the person which will die

    List<Integer> person = new ArrayList<>();
    
    // fill the person vector
    for (int i = 1; i <= n; i++) {
      person.add(i);
    }

    Josh(person, k, index);
  }
}

// This code is contributed by umadevi9616 
Python
# Python code for Josephus Problem
def Josh(person, k, index):
  
  # Base case , when only one person is left
  if len(person) == 1:
    print(person[0])
    return
  
  # find the index of first person which will die
  index = ((index+k)%len(person))
  
   # remove the first person which is going to be killed
  person.pop(index)
  
  # recursive call for n-1 persons
  Josh(person,k,index)

# Driver Program to test above function
n = 14 # specific n and k  values for original josephus problem
k = 2
k-=1   # (k-1)th person will be killed

index = 0 

# fill the person vector
person=[]
for i in range(1,n+1):
  person.append(i)

Josh(person,k,index)

# This code is contributed by
# Gaurav Kandel
C#
using System;
using System.Collections.Generic;
class GFG {
    
    static void Josh(List<int> person, int k, int index)
    {
        // Base case , when only one person is left
        if (person.Count == 1) {
            Console.WriteLine(person[0]);
            return;
        }
     
        // find the index of first person which will die
        index = ((index + k) % person.Count);
     
        // remove the first person which is going to be killed
        person.RemoveAt(index);
     
        // recursive call for n-1 persons
        Josh(person, k, index);
    }

  // Driver code
  static void Main()
  {
    int n = 14; // specific n and k  values for original
                // josephus problem
    int k = 2;
    k--; // (k-1)th person will be killed
    int index
        = 0; // The index where the person which will die
 
    List<int> person = new List<int>();
    // fill the person vector
    for (int i = 1; i <= n; i++) {
        person.Add(i);
    }
 
    Josh(person, k, index);
  }
}

// This code is contributed by divyesh072019.
JavaScript
<script>
    function Josh( person , k , index) {

        // Base case , when only one person is left
        if (person.length == 1) {
            document.write(person[0]);
            return;
        }

        // find the index of first person which will die
        index = ((index + k) % person.length);

        // remove the first person which is going to be killed
         if (index > -1) {
       person.splice(index, 1);
    }

        // recursive call for n-1 persons
        Josh(person, k, index);
    }

    // Driver code
    
        var n = 14; // specific n and k values for original
        // josephus problem
        var k = 2;
        k--; // (k-1)th person will be killed
        var index = 0; // The index where the person which will die

        var person = [];

        // fill the person vector
        for (var i = 1; i <= n; i++) {
            person.push(i);
        }

        Josh(person, k, index);
        
// This code is contributed by umadevi9616 
</script>

Output
13

Time Complexity: O(N2)
Auxiliary Space: O(N), For recursion stack

Approach to solve Josephus problem iteratively:

Illustration:

N = 5,  k = 2

Add all values from 1 to N in the list. We will call the recursive function with start = 0 and k = 1 (0-indexing)

Now the element at 1-index (person number 2) will be killed. And it is removed from the list. The new counting will begin from 1-index, the person at 1-index killed so now person at 2-index (person number 3) comes to 1-index and counting starts from here now.

Now we have 4 people, counting starting from 1-index (person number 3) and the person at kth (2-index ) position will be killed. 

The person at 2-index (person number 4) was killed so now we have 3 people left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here.

The person at the 0-index was killed and we have now two-person left in the circle. And the person at 1-index shifted to 0-index i.e. person number 3.

Final counting done and the person at 1-index killed and the only person who is left is at position 3.

Follow the below steps to Implement the idea:

  • Initialize variables num, cnt, and cut with 1, 0, and 0 respectively and an array arr[] of size N with the initial value set as 1.
  • Run a while loop till cnt < N:
    • Run a while loop till num is less than equal to k.
      • Increment cut by one and take modulo by N
      • If arr[cut] = 1 increment num by one.
    •  Set num = 1, arr[cut] = 0 and increment cnt and cut by one and cut = cut % n;
    • Run a while loop till arr[cut] = 0 and increment cut by one.
  • Return cnt + 1 as the required answer.

Below is the Implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

int Josephus(int, int);

int Josephus(int n, int k)
{
    k--;
    int arr[n];

    // Makes all the 'n' people alive by
    // assigning them value = 1
    for (int i = 0; i < n; i++) {
        arr[i] = 1;
    }
    int cnt = 0, cut = 0,
        // Cut = 0 gives the sword to 1st person.
        num = 1;

    // Loop continues till n-1 person dies.
    while (cnt < (n - 1)) {

        // Checks next (kth) alive persons.
        while (num <= k) {
            cut++;

            // Checks and resolves overflow
            // of Index.
            cut = cut % n;
            if (arr[cut] == 1) {
                // Updates the number of persons
                // alive.
                num++;
            }
        }

        // Refreshes value to 1 for next use.
        num = 1;

        // Kills the person at position of 'cut'
        arr[cut] = 0;

        // Updates the no. of killed persons.
        cnt++;
        cut++;

        // Checks and resolves overflow of Index.
        cut = cut % n;

        // Checks the next alive person the
        // sword is to be given.
        while (arr[cut] == 0) {
            cut++;

            // Checks and resolves overflow
            // of Index.
            cut = cut % n;
        }
    }

    // Output is the position of the last
    // man alive(Index + 1);
    return cut + 1;
}

// Driver code
int main()
{
    int n = 14, k = 2;
    cout << Josephus(n, k);
    return 0;
}

// THIS CODE IS PRESENTED BY SHISHANK RAWAT
Java
// Java code to implement the above approach
import java.io.*;
class GFG {

    public static void main(String[] args)
    {
        int n = 14, k = 2;
        System.out.println(Josephus(n, k));
    }

    public static int Josephus(int n, int k)
    {
        k--;
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = 1; // Makes all the 'n' people alive by
            // assigning them value = 1
        }
        int cnt = 0, cut = 0,
            num
            = 1; // Cut = 0 gives the sword to 1st person.
        while (
            cnt
            < (n
               - 1)) // Loop continues till n-1 person dies.
        {
            while (num
                   <= k) // Checks next (kth) alive persons.
            {
                cut++;
                cut = cut
                      % n; // Checks and resolves overflow
                // of Index.
                if (arr[cut] == 1) {
                    num++; // Updates the number of persons
                    // alive.
                }
            }
            num = 1; // refreshes value to 1 for next use.
            arr[cut] = 0; // Kills the person at position of
                          // 'cut'
            cnt++; // Updates the no. of killed persons.
            cut++;
            cut = cut % n; // Checks and resolves overflow
                           // of Index.
            while (arr[cut]
                   == 0) // Checks the next alive person the
            // sword is to be given.
            {
                cut++;
                cut = cut
                      % n; // Checks and resolves overflow
                // of Index.
            }
        }
        return cut
            + 1; // Output is the position of the last
        // man alive(Index + 1);
    }
}

// This code is contributed by Shubham Singh
Python
def Josephus(n, k):
    
    k -= 1
    arr = [0]*n
    for i in range(n):
        arr[i] = 1 # Makes all the 'n' people alive by
        # assigning them value = 1
    cnt = 0
    cut = 0
    num = 1 # Cut = 0 gives the sword to 1st person.
    while (cnt < (n - 1)):
      
        # Loop continues till n-1 person dies.
        while (num <= k):
          
            # Checks next (kth) alive persons.
            cut += 1
            cut = cut % n # Checks and resolves overflow
            # of Index.
            if (arr[cut] == 1):
                num+=1 # Updates the number of persons
                # alive.
        
        num = 1 # refreshes value to 1 for next use.
        arr[cut] = 0 # Kills the person at position of 'cut'
        cnt += 1 # Updates the no. of killed persons.
        cut += 1
        cut = cut % n # Checks and resolves overflow of Index.
        while (arr[cut] == 0):
          
            # Checks the next alive person the
            # sword is to be given.
            cut += 1
            cut = cut % n # Checks and resolves overflow
            # of Index.
    
    return cut + 1 # Output is the position of the last
                    # man alive(Index + 1)

# Driver Code
n, k = 14, 2 #map (int, input().splut())
print(Josephus(n, k))

# This code is contributed by ShubhamSingh 
C#
// C# code to implement the above approach
using System;
using System.Linq;

public class GFG{

  public static void Main ()
  {
    int n = 14, k = 2;
    Console.Write(Josephus(n, k));
  }

  public static int Josephus(int n, int k)
  {
    k--;
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
      arr[i] = 1; // Makes all the 'n' people alive by
      // assigning them value = 1
    }
    int cnt = 0, cut = 0,
    num = 1; // Cut = 0 gives the sword to 1st person.
    while (
      cnt
      < (n - 1)) // Loop continues till n-1 person dies.
    {
      while (num <= k) // Checks next (kth) alive persons.
      {
        cut++;
        cut = cut % n; 
        
        // Checks and resolves overflow
        // of Index.
        if (arr[cut] == 1)
        {
          num++; // Updates the number of persons
          // alive.
        }
      }
      num = 1; // refreshes value to 1 for next use.
      arr[cut]
        = 0; // Kills the person at position of 'cut'
      cnt++; // Updates the no. of killed persons.
      cut++;
      cut = cut
        % n; // Checks and resolves overflow of Index.
      while (arr[cut]
             == 0) // Checks the next alive person the
        // sword is to be given.
      {
        cut++;
        cut = cut % n; // Checks and resolves overflow
        // of Index.
      }
    }
    return cut + 1; // Output is the position of the last
    // man alive(Index + 1);
  }
}

// This code is contributed by Shubham Singh
JavaScript
<script>
    // Javascript code to implement the above approach
    
    let n = 14, k = 2;
    document.write(Josephus(n, k));
    
    function Josephus(n, k)
    {
      k--;
      let arr = new Array(n);
      for (let i = 0; i < n; i++)
      {
      
          // Makes all the 'n' people alive by
        // assigning them value = 1
        arr[i] = 1; 
      }
      
      // Cut = 0 gives the sword to 1st person.
      let cnt = 0, cut = 0,
      num = 1; 
      
      // Loop continues till n-1 person dies.
      while (cnt < (n - 1)) 
      {
      
       // Checks next (kth) alive persons.
        while (num <= k)
        {
          cut++;
          cut = cut % n;

          // Checks and resolves overflow
          // of Index.
          if (arr[cut] == 1)
          {
          
               // Updates the number of persons
            // alive.
            num++;
          }
        }
        
        // refreshes value to 1 for next use.
        num = 1; 
        arr[cut] = 0; // Kills the person at position of 'cut'
        
         // Updates the no. of killed persons.
        cnt++;
        cut++;
        
        // Checks and resolves overflow of Index.
        cut = cut % n; 
        
        // Checks the next alive person the
        // sword is to be given.
        while (arr[cut] == 0) 
        {
          cut++;
          
          // Checks and resolves overflow
          // of Index.
          cut = cut % n; 
        }
      }
      
       // Output is the position of the last
      // man alive(Index + 1);
      return cut + 1;
    }
  
  // This code is contributed by decode2207.
</script>

Output
13

Time Complexity: O(N2)
Auxiliary Space: O(N)

Josephus Problem in Linear Time and Constant Space:

Follow the below steps to Solve the Problem (Approach):

  • Initialize variables i and ans with 1 and 0 respectively.
  • Run a while loop till i <= N:
    • Update ans with (ans + k) % i.
    • Increment i by 1.
  • Return ans + 1 as the required answer.

Below is the Implementation of the above Steps:

C++
// C++ code to Implement Josephus Problem

#include <iostream>
using namespace std;

int Josephus(int N, int k)
{

    // Initialize variables i and ans with 1 and 0
    // respectively.

    int i = 1, ans = 0;

    // Run a while loop till i <= N

    while (i <= N) {

        // Update the Value of ans and Increment i by 1
        ans = (ans + k) % i;
        i++;
    }

    // Return required answer
    return ans + 1;
}

// main function
int main()
{

    int N = 14, k = 2;
    cout << Josephus(N, k) << endl;
    return 0;
}

// This code is presented by Akash Mangal
C
// C Program to Implement Josephus Problem

#include <stdio.h>

int Josephus(int N, int k)
{

    // Initialize variables i and ans with 1 and 0
    // respectively.

    int i = 1, ans = 0;

    // Run a while loop till i <= N

    while (i <= N) {

        // Update the Value of ans and Increment i by 1
        ans = (ans + k) % i;
        i++;
    }

    // Return required answer
    return ans + 1;
}

// main function
int main()
{

    int N = 14, k = 2;
    printf("%d", Josephus(N, k));
    return 0;
}

// This code is presented by Akash Mangal
Java
// Java code to Implement Josephus Problem
import java.io.*;

class GFG {
  public static int Josephus(int N, int k) {

    // Initialize variables i and ans with 1 and 0 respectively.
    int i = 1, ans = 0;

    // Run a while loop till i <= N
    while (i <= N) {

      // Update the Value of ans and Increment i by 1
      ans = (ans + k) % i;
      i++;
    }

    // Return required answer
    return ans + 1;
  }


  // main function
  public static void main (String[] args) {

    int N = 14, k = 2;
    int ans = Josephus(N, k);
    System.out.println(ans);
  }
}

// This code is presented by Akash Mangal
Python
# python code to implement Josephus problem 

# Josephus function which will take 
# two parameter N and K, number of people and positions respectively
# return the position of person survives
def Josephus(n, k):

    # initialize two variables i and ans
    i = 1
    ans = 0
    while(i <= n):

        # update the value of ans
        ans = (ans + k) % i
        i += 1
    
    # returning the required answer
    return ans + 1

# driver code
# let 
n = 14
k = 2

result = Josephus(n, k)
print(result)

# This code is contributed by sarveshc111.
C#
// C# code to Implement Josephus Problem
using System;

class GFG
{
    public static int Josephus(int N, int k)
    {
        // Initialize variables i and ans with 1 and 0 respectively.
        int i = 1, ans = 0;

        // Run a while loop till i <= N
        while (i <= N)
        {
            // Update the Value of ans and Increment i by 1
            ans = (ans + k) % i;
            i++;
        }

        // Return required answer
        return ans + 1;
    }


    // main function
    static void Main(string[] args)
    {
        int N = 14, k = 2;
        int ans = Josephus(N, k);
        Console.WriteLine(ans);
    }
}
JavaScript
// driver code
let n = 14, k = 2;
document.write(Josephus(n,k));

// Josephus function 
// return the position of last man survives
function Josephus(n, k)
{
    let i = 1, ans = 0;
    while(i <= n ){

        // update the value of ans 
        ans = (ans + k) % i;
        i++;
    }
    return ans + 1;
}

// This code is contributed by sarveshc111.

Output
13

Time Complexity: O(N)
Auxiliary Space: O(1)

Josephus Problem using Recursion:

Below is the idea to solve the problem:

The problem has the following recursive structure. josephus(n, k) = (josephus(n – 1, k) + k-1) % n + 1 and josephus(1, k) = 1

After the first person (kth from the beginning) is killed, n-1 persons are left. Make recursive call for Josephus(n – 1, k) to get the position with n-1 persons. But the position returned by Josephus(n – 1, k) will consider the position starting from k%n + 1. So make adjustments to the position returned by Josephus(n – 1, k). 

Below is the Implementation of the above idea.

C++
// C++ code to implement the idea

#include <bits/stdc++.h>
using namespace std;

// Recursive function to implement the Josephus problem
int josephus(int n, int k)
{
    if (n == 1)
        return 1;
    else
        // The position returned by josephus(n - 1, k)
        // is adjusted because the recursive call
        // josephus(n - 1, k) considers the
        // original position k % n + 1 as position 1
        return (josephus(n - 1, k) + k - 1) % n + 1;
}

// Driver code
int main()
{
    int n = 14;
    int k = 2;
    cout << "The chosen place is " << josephus(n, k);
    return 0;
}

// This code is contributed by shubhamsingh10
C
#include <stdio.h>

int josephus(int n, int k)
{
    if (n == 1)
        return 1;
    else
        /* The position returned by josephus(n - 1, k) is
           adjusted because the recursive call josephus(n -
           1, k) considers the original position
           k%n + 1 as position 1 */
        return (josephus(n - 1, k) + k - 1) % n + 1;
}

// Driver Program to test above function
int main()
{
    int n = 14;
    int k = 2;
    printf("The chosen place is %d", josephus(n, k));
    return 0;
}
Java
// Java code for Josephus Problem
import java.io.*;

class GFG {

    static int josephus(int n, int k)
    {
        if (n == 1)
            return 1;
        else
            /* The position returned by josephus(n - 1, k)
            is adjusted because the recursive call
            josephus(n - 1, k) considers the original
            position k%n + 1 as position 1 */
            return (josephus(n - 1, k) + k - 1) % n + 1;
    }

    // Driver Program to test above function
    public static void main(String[] args)
    {
        int n = 14;
        int k = 2;
        System.out.println("The chosen place is "
                           + josephus(n, k));
    }
}

// This code is contributed by Prerna Saini
Python3
# Python code for Josephus Problem


def josephus(n, k):

    if (n == 1):
        return 1
    else:

        # The position returned by
        # josephus(n - 1, k) is adjusted
        # because the recursive call
        # josephus(n - 1, k) considers
        # the original position
        # k%n + 1 as position 1
        return (josephus(n - 1, k) + k-1) % n + 1

# Driver Program to test above function


n = 14
k = 2

print("The chosen place is ", josephus(n, k))

# This code is contributed by
# Sumit Sadhakar
C#
// C# code for Josephus Problem
using System;

class GFG {

    static int josephus(int n, int k)
    {
        if (n == 1)
            return 1;
        else
            /* The position returned
            by josephus(n - 1, k) is
            adjusted because the
            recursive call josephus(n
            - 1, k) considers the
            original position k%n + 1
            as position 1 */
            return (josephus(n - 1, k) + k - 1) % n + 1;
    }

    // Driver Program to test above
    // function
    public static void Main()
    {
        int n = 14;
        int k = 2;
        Console.WriteLine("The chosen "
                          + "place is " + josephus(n, k));
    }
}

// This code is contributed by anuj_67.
JavaScript
<script>

    // Javascript code for Josephus Problem
    
    function josephus(n, k)
    {
        if (n == 1)
            return 1;
        else
            /* The position returned
            by josephus(n - 1, k) is
            adjusted because the
            recursive call josephus(n
            - 1, k) considers the
            original position k%n + 1
            as position 1 */
            return (josephus(n - 1, k)
                       + k-1) % n + 1;
    }
      
    let n = 14;
    let k = 2;
    document.write("The chosen " + "place is " + josephus(n, k));
    
</script>
PHP
<?php
// PHP code for 
// Josephus Problem

function josephus($n, $k)
{
    if ($n == 1)
        return 1;
    else
        /* The position returned by 
           josephus(n - 1, k) is 
           adjusted because the
           recursive call josephus
           (n - 1, k) considers the 
           original position k%n + 1 
           as position 1 */
        return (josephus($n - 1, $k) + 
                    $k - 1) % $n + 1;
}

    // Driver Code
    $n = 14;
    $k = 2;
    echo "The chosen place is ", josephus($n, $k);

// This code is contributed by ajit.
?>

Output
The chosen place is 13

Time Complexity: O(N)
Auxiliary Space: O(N) the space used in recursion call stack

Please visit set-2: Josephus problem | Set 2 (A Simple Solution when k = 2)



Similar Reads

Josephus Problem | (Iterative Solution)
There are N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N. The game starts going in circles counting the children starting with the first chair. Once the count reaches K, that child leaves the game, removing his/her chair. The game starts again, beginning with the next chair in the circle. The last ch
9 min read
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
7 min read
Josephus Problem when k is 2
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the execut
12 min read
Josephus Problem Using Bit Magic
The Problem This problem is named after Flavius Josephus a Jewish historian who fought against the Romans. According to Josephus he and his group of Jewish soldiers were cornered & surrounded by the Romans inside a cave, and they choose to murder and suicide inside of surrender and capture. They decided that all the soldiers will sit in a circl
14 min read
CSES Solutions - Josephus Problem I
Consider a game where there are N children (numbered 1,2 ... N) in a circle. During the game, every other child is removed from the circle until there are no children left. In which order will the children be removed? Examples: Input: N = 7Output: 2 4 6 1 5 3 7Explanation: Children = {1, 2, 3, 4, 5, 6, 7}, 1 is skipped and 2 is removed.Children = {
5 min read
CSES Solutions - Josephus Problem II
Consider a game where there are N children (numbered 1,2 ... N) in a circle. During the game, repeatedly K children are skipped and one child is removed from the circle. In which order will the children be removed? Examples: Input: N = 7, K = 2Output: 3 6 2 7 5 1 4Explanation: children = [1, 2, 3, 4, 5, 6, 7], 1 and 2 are skipped and 3 is removed.
11 min read
Josephus Circle implementation using STL list
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the execut
6 min read
CSES Solutions - Josephus Queries
Consider a game where there are n children (numbered 1,2,...n) in a circle. During the game, every second child is removed from the circle, until there are no children left. Your task is to process q queries of the form: "when there are n children, who is the kth child that will be removed?" Example: Input: totalChildren = 7, kthChild = 1;Output: 2
6 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
8 queen problem
The eight queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an n×n chessboard. There are different solutions for the problem. Backtracking | Set 3 (N Queen Problem) Branch and
8 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Custom Tree Problem
You are given a set of links, e.g. a ---> b b ---> c b ---> d a ---> e Print the tree that would form when each pair of these links that has the same character as start and end point is joined together. You have to maintain fidelity w.r.t. the height of nodes, i.e. nodes at height n from root should be printed at same row or column. For
13 min read
Stable Marriage Problem
The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are
15+ min read
Approximate solution for Travelling Salesman Problem using MST
We introduced Travelling Salesman Problem and discussed Naive and Dynamic Programming Solutions for the problem in the previous post,. Both of the solutions are infeasible. In fact, there is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There are approximate algorithms to solve the problem though.
3 min read
Channel Assignment Problem
There are M transmitter and N receiver stations. Given a matrix that keeps track of the number of packets to be transmitted from a given transmitter to a receiver. If the (i; j)-th entry of the matrix is k, it means at that time the station i has k packets for transmission to station j. During a time slot, a transmitter can send only one packet and
14 min read
Steiner Tree Problem
What is Steiner Tree? The Steiner Tree Problem is known to be NP-hard, which means that it is unlikely that there is an efficient algorithm that can solve the problem for large instances. However, there are several approximation algorithms that can provide a suboptimal solution with a guarantee on the quality of the solution. One popular approximat
6 min read
Word Break Problem | DP-32 | Set - 2
Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples: Input: S = "catsanddog" dict[] = {"cat", "cats", "and", "sand", "dog"} Output: "cats and dog" "cat sand dog"Input: S = "pineapplepenapple" dict[] = {"apple", "pen", "applep
15 min read
Maths behind number of paths in matrix problem
The problem is to count all the possible paths from top left to bottom right of an m*n matrix with the constraints that from each cell you can either move only towards right or down. First of all read various possible solutions for the stated problem here Now for the last solution, the combination formula for computing number of paths is given as m
2 min read
Program for Bridge and Torch problem
Given an array of positive distinct integer denoting the crossing time of 'n' people. These 'n' people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person's pace. Find the minimum total time in which all persons can cross the bridge. See this puzzle t
15+ min read
Job Selection Problem - Loss Minimization Strategy | Set 2
We have discussed one loss minimization strategy before: Job Sequencing Problem – Loss Minimization. In this article, we will look at another strategy that applies to a slightly different problem.We are given a sequence of N goods of production numbered from 1 to N. Each good has a volume denoted by (Vi). The constraint is that once a good has been
9 min read
Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
Minimum spanning Tree (MST) is an important topic for GATE. Therefore, we will discuss how to solve different types of questions based on MST. Before understanding this article, you should understand basics of MST and their algorithms (Kruskal’s algorithm and Prim’s algorithm). Type 1. Conceptual questions based on MST - There are some important pr
5 min read
Problem on permutations and combinations | Set 2
Prerequisite : Permutation and Combination Given a polygon of m sides, count number of triangles that can be formed using vertices of polygon. Answer : [m (m - 1)(m - 2) / 6] Explanation : There are m vertices in a polygon with m sides. We need to count different combinations of three points chosen from m. So answer is mC3 = m * (m - 1) * (m - 2) /
4 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Water drop problem
Consider a pipe of length L. The pipe has N water droplets at N different positions within it. Each water droplet is moving towards the end of the pipe(x=L) at different rates. When a water droplet mixes with another water droplet, it assumes the speed of the water droplet it is mixing with. Determine the no of droplets that come out of the end of
10 min read
Sequence Alignment problem
Given as an input two strings, [Tex]X [/Tex]= [Tex]x_{1} x_{2}... x_{m} [/Tex], and [Tex]Y [/Tex]= [Tex]y_{1} y_{2}... y_{m} [/Tex], output the alignment of the strings, character by character, so that the net penalty is minimized. The penalty is calculated as: A penalty of [Tex]p_{gap} [/Tex]occurs if a gap is inserted between the string. A penalt
15+ min read