Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Josephus Circle implementation using STL list
Next article icon

Josephus Circle implementation using STL list

Last Updated : 23 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 person n and a number k which indicates that k-1 persons are skipped and the kth person is killed in the circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive. (0-based indexing) .

Examples : 

Input : Length of circle : n = 4         Count to choose next : k = 2 Output : 0  Input : n = 5         k = 3 Output : 3

We have already discussed different solutions to this problem (here, here, and here). In this post, a  C++ STL-based solution using a list container is discussed which uses the idea of a circular list.

Implementation:

C++
// CPP program to find last man standing #include <bits/stdc++.h> using namespace std;  int josephusCircle(int n, int k){     list<int>l; //creates a doubly linked list using stl container//      for(int i=0;i<n;i++)         l.push_back(i); //pushes i to the end of the doubly linked list//            auto it = l.begin();       while(l.size()>1){                  for(int i=1;i<k;i++){             it++;                          if(it==l.end()){               //if iterator reaches the end,then we change it to begin of the list//                 it = l.begin();             }         }                   it = l.erase(it);                    if(it==l.end()){            //if iterator reaches the end,then we change it to begin of the list//                 it = l.begin();             }     }          return l.front(); //returns front element of the list//      } /* Driver program to test above functions */ int main() {    int n=14,k=2;              cout<<josephusCircle(n,k)<<"\n";        return 0; } 
Java
// Java Code to find the last man Standing  public class GFG {          // Node class to store data      static class Node     {         public int data ;         public Node next;         public Node( int data )         {             this.data = data;         }     }          /* Function to find the only person left     after one in every m-th node is killed     in a circle of n nodes */     static void getJosephusPosition(int m, int n)     {         // Create a circular linked list of         // size N.         Node head = new Node(0);         Node prev = head;         for(int i = 1; i < n; i++)         {             prev.next = new Node(i);             prev = prev.next;         }                  // Connect last node to first         prev.next = head;                  /* while only one node is left in the         linked list*/         Node ptr1 = head, ptr2 = head;                  while(ptr1.next != ptr1)         {                          // Find m-th node             int count = 1;             while(count != m)             {                 ptr2 = ptr1;                 ptr1 = ptr1.next;                 count++;             }                          /* Remove the m-th node */             ptr2.next = ptr1.next;             ptr1 = ptr2.next;         }         System.out.println ("Last person left standing " +                  "(Josephus Position) is " + ptr1.data);     }          /* Driver program to test above functions */     public static void main(String args[])     {         int n = 14, m = 2;         getJosephusPosition(m, n);     } } 
Python3
# Python3 program to find last man standing  # /* structure for a node in circular #    linked list */ class Node:     def __init__(self, x):         self.data = x         self.next = None  # /* Function to find the only person left #    after one in every m-th node is killed #    in a circle of n nodes */ def getJosephusPosition(m, n):        # Create a circular linked list of     # size N.     head = Node(0)     prev = head     for i in range(1, n):         prev.next = Node(i)         prev = prev.next     prev.next = head # Connect last                        #node to first      #/* while only one node is left in the     #linked list*/     ptr1 = head     ptr2 = head     while (ptr1.next != ptr1):         # Find m-th node         count = 1         while (count != m):             ptr2 = ptr1             ptr1 = ptr1.next             count += 1          # /* Remove the m-th node */         ptr2.next = ptr1.next         # free(ptr1)         ptr1 = ptr2.next      print("Last person left standing (Josephus Position) is ", ptr1.data)  # /* Driver program to test above functions */ if __name__ == '__main__':     n = 14     m = 2     getJosephusPosition(m, n)  # This code is contributed by mohit kumar 29 
C#
// C# Code to find the last man Standing  using System; public class GFG {           // Node class to store data      class Node      {          public int data ;          public Node next;          public Node( int data )          {              this.data = data;          }      }           /* Function to find the only person left      after one in every m-th node is killed      in a circle of n nodes */     static void getJosephusPosition(int m, int n)      {          // Create a circular linked list of          // size N.          Node head = new Node(0);          Node prev = head;          for(int i = 1; i < n; i++)          {              prev.next = new Node(i);              prev = prev.next;          }                   // Connect last node to first          prev.next = head;                   /* while only one node is left in the          linked list*/         Node ptr1 = head, ptr2 = head;                   while(ptr1.next != ptr1)          {                           // Find m-th node              int count = 1;              while(count != m)              {                  ptr2 = ptr1;                  ptr1 = ptr1.next;                  count++;              }                           /* Remove the m-th node */             ptr2.next = ptr1.next;              ptr1 = ptr2.next;          }          Console.WriteLine ("Last person left standing " +                  "(Josephus Position) is " + ptr1.data);      }           /* Driver program to test above functions */      static public void Main(String []args)      {          int n = 14, m = 2;          getJosephusPosition(m, n);      }  }  //contributed by Arnab Kundu 
JavaScript
<script> // javascript Code to find the last man Standing         // Node class to store data class Node {     constructor(val) {         this.data = val;         this.next = null;     } }      /*      * Function to find the only person left after one in every m-th node is killed      * in a circle of n nodes      */     function getJosephusPosition(m , n) {         // Create a circular linked list of         // size N. var head = new Node(0); var prev = head;         for (i = 1; i < n; i++) {             prev.next = new Node(i);             prev = prev.next;         }          // Connect last node to first         prev.next = head;          /*          * while only one node is left in the linked list          */ var ptr1 = head, ptr2 = head;          while (ptr1.next != ptr1) {              // Find m-th node             var count = 1;             while (count != m) {                 ptr2 = ptr1;                 ptr1 = ptr1.next;                 count++;             }              /* Remove the m-th node */             ptr2.next = ptr1.next;             ptr1 = ptr2.next;         }         document.write("Last person left standing " + "(Josephus Position) is " + ptr1.data);     }      /* Driver program to test above functions */              var n = 14, m = 2;         getJosephusPosition(m, n);  // This code is contributed by umadevi9616 </script> 

Output
12

Time complexity: O(k * n), as we are using nested loops to traverse k*n time. 
Auxiliary Space: O(n), as we are using extra space for the linked list.

This article is Improved by Mechanizer.  


Next Article
Josephus Circle implementation using STL list

R

Raghav Sharma 5
Improve
Article Tags :
  • Linked List
  • DSA
  • circular linked list
Practice Tags :
  • circular linked list
  • Linked List

Similar Reads

    Circular Linked List Implementation of Circular Queue
    The task is to implement the circular queue with the following operations using a circular linked list.Operations on Circular Queue:Front: Get the front item from the queue.Rear: Get the last item from the queue.enQueue(value): This function is used to insert an element into the circular queue. In a
    10 min read
    Circular Array Implementation of Queue
    A Circular Queue is a way of implementing a normal queue where the last element of the queue is connected to the first element of the queue forming a circle.The operations are performed based on the FIFO (First In First Out) principle. It is also called 'Ring Buffer'. In a normal Queue, we can inser
    8 min read
    Geometry using Complex Numbers <std::complex> in C++ | Set 1
    While solving geometric problems, it is time consuming to define the point class for specifying a point on the 2D Plane or the Euclidean Plane. So, this article specifies a faster and clever way to implement the same using complex class from STL in C++. Before implementation, it is essential to unde
    5 min read
    Insertion in Circular Singly Linked List
    In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the list. In a circular linked list, the last node connects back to the first node, creating a loop.There are four main ways to add
    12 min read
    Convert singly linked list into circular linked list
    Given a singly linked list, the task is to convert it into a circular linked list.Examples:Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head.Input: head: 2 -> 4 -> 6 -> 8 -> 10 -
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences