Josephus problem using queue

Queue simulation solves Josephus neatly: keep people in a queue, move first k-1 people to rear, eliminate the kth, and repeat until one survivor remains.

On this page
  • Queue-based elimination idea
  • C implementation
  • Step trace and survivor

1) Algorithm

StepAction
1Enqueue persons 1..n.
2Repeat while size > 1: rotate k-1 times (front to rear).
3Dequeue next person (eliminated).
4Remaining front is survivor.

2) Example in C

#include <stdio.h>

#define MAX 200
int q[MAX], f = 0, r = -1, sz = 0;
void enq(int x){ q[++r] = x; sz++; }
int deq(void){ sz--; return q[f++]; }

int josephus(int n, int k){
    f = 0; r = -1; sz = 0;
    for(int i=1;i<=n;i++) enq(i);
    while(sz > 1){
        for(int i=1;i<k;i++) enq(deq());
        printf("Eliminated: %d\n", deq());
    }
    return deq();
}

int main(void){
    int n = 7, k = 3;
    int ans = josephus(n, k);
    printf("Survivor: %d\n", ans);
    return 0;
}

Execution summary (n=7, k=3)

RoundEliminatedQueue State (conceptual)
13[4,5,6,7,1,2]
26[7,1,2,4,5]
32[4,5,7,1]
47[1,4,5]
55[1,4]
61[4]

3) Complexity

  • Time: O(nk) for direct simulation.
  • Space: O(n) for queue.

Key takeaway

Josephus is a strong queue-rotation pattern problem: repeated front-to-rear moves + periodic dequeue.