Introduction
The Josephus Problem involves eliminating people in circular order.
Given:
- n people standing in a circle
- every k-th person is eliminated
The task is to:
- find the last surviving person
This problem is one of the most important applications of:
Queue Simulation + Circular TraversalThis problem helps in understanding:
- circular queues
- recursion
- elimination logic
- mathematical recurrence relations
Example
Input:n = 5 k = 2
Output: 3
Explanation: People: 1 2 3 4 5
Elimination Order: 2 → 4 → 1 → 5
Remaining person: 3
Constraints
1 <= n <= 5001 <= k <= 500
Approach 1 : Queue Simulation
Explanation
The simplest way is:
- Place all people in queue
- Rotate queue k-1 times
- Remove k-th person
- Repeat until one person remains
This directly simulates elimination.
Steps
- Insert all people into queue.
- Rotate first k-1 people.
- Remove front person.
- Continue until one remains.
- Return survivor.
Dry Run
Input:n = 5
k = 2
Queue: 1 2 3 4 5
Rotate: 1 moves back
Remove: 2
Queue: 3 4 5 1
Continue process...
Remaining: 3
Queue Simulation Code
Complexity Analysis
Time Complexity: O(n * k)
Explanation:
Queue rotations occur repeatedly.
Space Complexity: O(n)
Explanation:
Queue stores all people.Approach 2 : Mathematical Recursion
Explanation
The optimized solution uses:
Josephus Recurrence RelationThe recurrence formula is:
f(n,k) = (f(n-1,k) + k) % nBase Case:
f(1,k) = 0Final answer:
- add 1
for 1-based indexing
This avoids full simulation.
Steps
- Define recursive formula.
- Solve smaller subproblem.
- Shift survivor position.
- Return final answer.
Dry Run
n = 1Survivor = 0
n = 2
(0 + 2) % 2 = 0
n = 3 (0 + 2) % 3 = 2
n = 4 (2 + 2) % 4 = 0
n = 5 (0 + 2) % 5 = 2
Final Answer: 2 + 1 = 3
Mathematical Recursion Code
Complexity Analysis
Time Complexity: O(n)
Explanation:
Recurrence is solved once for every person.
Space Complexity: O(n)
Explanation:
Recursive stack space is used.