Open In App

CSES Solutions – Josephus Problem I

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 = 7
Output: 2 4 6 1 5 3 7
Explanation:

  • Children = {1, 2, 3, 4, 5, 6, 7}, 1 is skipped and 2 is removed.
  • Children = {1, 3, 4, 5, 6, 7}, 3 is skipped and 4 is removed.
  • Children = {1, 3, 5, 6, 7}, 5 is skipped and 6 is removed.
  • Children = {1, 3, 5, 7}, 7 is skipped and 1 is removed.
  • Children = {3, 5, 7}, 3 is skipped and 5 is removed.
  • Children = {3, 7}, 7 is skipped and 3 is removed.
  • Children = {7}, 7 is skipped and removed.

Input: N = 6
Output: 2 4 6 3 1 5
Explanation:

  • Children = {1, 2, 3, 4, 5, 6}, 1 is skipped and 2 is removed.
  • Children = {1, 3, 4, 5, 6}, 3 is skipped and 4 is removed.
  • Children = {1, 3, 5, 6}, 5 is skipped and 6 is removed.
  • Children = {1, 3, 5}, 1 is skipped and 3 is removed.
  • Children = {1, 5}, 5 is skipped and 1 is removed.
  • Children = {5}, 5 is skipped and removed.

Approach: To solve the problem, follow the below idea:

The problem can be solved using a Queue to simulate the removal of elements. Initially, we will push all the elements into the queue in order 1 to N. Now, we can take a flag which we can toggle after every element as we want to remove only the alternate elements. So, if the flag is true, we remove the current element and toggle flag to false so that the next element does not get removed. Now, for the next element the flag is false, so we don’t remove that element and set the flag to true so that the next element gets removed. After popping the element from the queue, if flag = true we will print the element otherwise we will push the element back to the queue.

Step-by-step algorithm:

  • Declare a Queue q and push all the children into the queue.
  • Also declare a flag to decide whether to remove the current child or not (Initially set to false).
  • Now, one by one pop the element at the front of the queue.
    • If the element is supposed to be removed from the queue, we print the element.
    • Otherwise, we push the element back to the queue.
  • All the elements will be printed in the order as they are deleted.

Below is the implementation of the algorithm:

C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;

void solve(ll N)
{
    queue<ll> q;
    // Push all the children to the queue
    for (int i = 1; i <= N; i++)
        q.push(i);

    // Set the flag to false, so that the first child does
    // not get removed
    bool flag = false;

    while (!q.empty()) {
        int ele = q.front();
        q.pop();
        // If we have to remove the element, print it
        if (flag) {
            cout << ele << " ";
        }
        // If we don't have to remove the element, push it
        // back to the queue
        else {
            q.push(ele);
        }
        // Toggle the value of flag so that only the
        // alternate elements get removed
        flag = !flag;
    }
}

int main()
{
    ll N = 7;
    solve(N);
}
Java
import java.util.LinkedList;
import java.util.Queue;

public class Main {

    static void solve(long N) {
        Queue<Long> q = new LinkedList<>();

        // Push all the children to the queue
        for (long i = 1; i <= N; i++)
            q.add(i);

        // Set the flag to false, so that the first child does
        // not get removed
        boolean flag = false;

        while (!q.isEmpty()) {
            long ele = q.poll();
            // If we have to remove the element, print it
            if (flag) {
                System.out.print(ele + " ");
            }
            // If we don't have to remove the element, push it
            // back to the queue
            else {
                q.add(ele);
            }
            // Toggle the value of flag so that only the
            // alternate elements get removed
            flag = !flag;
        }
    }

    public static void main(String[] args) {
        long N = 7;
        solve(N);
    }
}

// This code is contributed by shivamgupta0987654321
Python
from collections import deque

def solve(N):
    q = deque(range(1, N+1))
    flag = False

    while q:
        ele = q.popleft()
        if flag:
            print ele,
        else:
            q.append(ele)
        flag = not flag

N = 7
solve(N)
C#
using System;
using System.Collections.Generic;

class Program
{
    static void Solve(long N)
    {
        Queue<long> q = new Queue<long>();
        
        // Push all the children to the queue
        for (long i = 1; i <= N; i++)
            q.Enqueue(i);

        // Set the flag to false, so that the first child does
        // not get removed
        bool flag = false;

        while (q.Count > 0)
        {
            long ele = q.Dequeue();
            
            // If we have to remove the element, print it
            if (flag)
            {
                Console.Write(ele + " ");
            }
            // If we don't have to remove the element, push it
            // back to the queue
            else
            {
                q.Enqueue(ele);
            }

            // Toggle the value of flag so that only the
            // alternate elements get removed
            flag = !flag;
        }
    }

    static void Main(string[] args)
    {
        long N = 7;
        Solve(N);
    }
}
JavaScript
function solve(N) {
    let q = [];
    for (let i = 1; i <= N; i++) {
        q.push(i);
    }
    let flag = false;

    while (q.length > 0) {
        let ele = q.shift();
        if (flag) {
            console.log(ele);
        } else {
            q.push(ele);
        }
        flag = !flag;
    }
}

const N = 7;
solve(N);

Output
2 4 6 1 5 3 7 

Time Complexity: O(2 * N) = O(N), where N is the number of children.
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

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
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
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
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
26 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 &amp; 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
Josephus Problem | Set 3 (using STL)
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
12 min read
CSES Problem Set Solutions
In this article, we have compiled comprehensive, high-quality tutorials on the CSES Problem Set Solutions to assist you in understanding the problem set for learning algorithmic programming. What is CSES Problem Set?CSES Problem Set is a collection of competitive programming tasks hosted on the CSES website. These problems cover a wide range of top
8 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
Practice Tags :