githubEdit

24. Josephus Problem

โœ… GFG solution to the Josephus Problem: find the survivor's position in a circular elimination game using iterative DP, recursion, and mathematical optimization. ๐Ÿš€

The problem can be found at the following link: ๐Ÿ”— Question Linkarrow-up-right

๐Ÿงฉ Problem Description

You are playing a game with n people standing in a circle, numbered from 1 to n. Starting from person 1, every kth person is eliminated in a circular fashion. The process continues until only one person remains.

Given integers n and k, return the position (1-based index) of the person who will survive.

๐Ÿ“˜ Examples

Example 1

Input: n = 5, 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.

Example 2

Input: n = 7, k = 3
Output: 4
Explanation: The elimination order is 3 โ†’ 6 โ†’ 2 โ†’ 7 โ†’ 5 โ†’ 1, and the person at position 4 survives.

๐Ÿ”’ Constraints

  • $1 \le n, k \le 500$

โœ… My Approach

The optimal approach uses Iterative Dynamic Programming to build the solution from the base case upward:

Iterative DP Solution

  1. Base Case Understanding:

    • When only 1 person remains (n=1), the survivor is at position 0 in 0-indexed notation.

    • We need to convert this to 1-indexed for the final answer.

  2. Build Solution Iteratively:

    • Start with the base case: pos = 0 (survivor position for 1 person in 0-indexed).

    • For each number of people from 2 to n, calculate the survivor position.

    • Use the recurrence relation: pos = (pos + k) % i, where i is the current number of people.

  3. Mathematical Insight:

    • After eliminating one person from a circle of n people, we have n-1 people remaining.

    • The problem reduces to finding the survivor in a circle of n-1 people.

    • The position shifts by k due to the elimination pattern.

    • The modulo operation handles the circular nature of the arrangement.

  4. Convert to 1-Based Index:

    • Add 1 to the final 0-indexed position to get the 1-based answer.

๐Ÿ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we iterate from 2 to n, performing constant-time operations in each iteration to calculate the survivor position.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space to store the position variable and loop counter, independent of input size.

โš™๏ธ Code (C)

๐Ÿง‘โ€๐Ÿ’ป Code (C++)

chevron-rightโšก View Alternative Approaches with Code and Analysishashtag

๐Ÿ“Š 2๏ธโƒฃ Recursive Approach

๐Ÿ’ก Algorithm Steps:

  1. Base case: If only one person remains (n=1), they are at position 1.

  2. Recursively solve for n-1 people to find the survivor position in a smaller circle.

  3. Adjust the position by adding k steps and taking modulo n to handle circular wrapping.

  4. Convert from 0-indexed to 1-indexed result by proper adjustment.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(n) - Makes n recursive calls, one for each person eliminated

  • Auxiliary Space: ๐Ÿ’พ O(n) - Recursion call stack depth proportional to number of people

โœ… Why This Approach?

  • Intuitive recursive logic that directly mirrors the problem definition

  • Natural translation from the mathematical recurrence relation

  • Easy to understand the step-by-step elimination process

  • Good for educational purposes and small inputs

๐Ÿ“Š 3๏ธโƒฃ Zero-Indexed Iterative

๐Ÿ’ก Algorithm Steps:

  1. Initialize position to 0, representing the survivor in a circle of 1 person (0-indexed).

  2. Iteratively build solution from 1 to n people, updating position at each step.

  3. Use the formula: pos = (pos + k) % i where i is the current circle size.

  4. Convert final 0-indexed position to 1-indexed by adding 1.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(n) - Single loop iterating through all circle sizes from 1 to n

  • Auxiliary Space: ๐Ÿ’พ O(1) - Only uses a constant number of variables

โœ… Why This Approach?

  • Clean separation between 0-indexed calculation and final conversion

  • Standard iterative dynamic programming pattern with clear logic flow

  • Minimal variable usage maximizes cache efficiency

  • Easier to trace and debug compared to recursion

๐Ÿ“Š 4๏ธโƒฃ Mathematical Direct Formula (k=2)

๐Ÿ’ก Algorithm Steps:

  1. Special optimization when k equals 2 (every second person eliminated).

  2. Find the highest power of 2 that is less than or equal to n.

  3. Calculate survivor position using closed-form formula: 2 * (n - power_of_2) + 1.

  4. For general k, fall back to iterative approach.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(log n) for k=2 due to power-of-2 calculation, O(n) for general k

  • Auxiliary Space: ๐Ÿ’พ O(1) - Uses constant extra space regardless of input size

โœ… Why This Approach?

  • Extremely efficient for the common k=2 case with logarithmic time

  • Demonstrates deep mathematical insight into the problem structure

  • Useful for competitive programming where k=2 is frequently tested

  • Shows how problem-specific optimizations can dramatically improve performance

๐Ÿ†š ๐Ÿ” Comparison of Approaches

๐Ÿš€ Approach

โฑ๏ธ Time Complexity

๐Ÿ’พ Space Complexity

โœ… Pros

โš ๏ธ Cons

๐Ÿ” Iterative DP

๐ŸŸข O(n)

๐ŸŸข O(1)

๐Ÿš€ Optimal space, no stack risk

๐Ÿ”ง Less intuitive than recursion

๐Ÿ”„ Recursive

๐ŸŸข O(n)

๐ŸŸก O(n)

๐Ÿ“– Natural problem mapping

๐Ÿ’พ Stack overflow risk for large n

0๏ธโƒฃ Zero-Indexed

๐ŸŸข O(n)

๐ŸŸข O(1)

๐ŸŽฏ Clean separation of concerns

๐Ÿ”ง Extra conversion step

๐Ÿงฎ Math Formula (k=2)

๐ŸŸข O(log n)

๐ŸŸข O(1)

โญ Lightning fast for k=2

๐Ÿ“ Only works for specific k value

๐Ÿ† Best Choice Recommendation

๐ŸŽฏ Scenario

๐ŸŽ–๏ธ Recommended Approach

๐Ÿ”ฅ Performance Rating

๐Ÿ… General optimal solution

๐Ÿฅ‡ Iterative DP

โ˜…โ˜…โ˜…โ˜…โ˜…

๐Ÿ“– Learning/Understanding

๐Ÿฅˆ Recursive

โ˜…โ˜…โ˜…โ˜…โ˜†

๐Ÿ”ง Code clarity and debugging

๐Ÿฅ‰ Zero-Indexed

โ˜…โ˜…โ˜…โ˜…โ˜†

๐ŸŽฏ Competitive programming (k=2)

๐Ÿ… Math Formula

โ˜…โ˜…โ˜…โ˜…โ˜…

โ˜• Code (Java)

๐Ÿ Code (Python)

๐Ÿง  Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐Ÿ“ฌ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

โญ If you find this helpful, please give this repository a star! โญ


๐Ÿ“Visitor Count

Visitor counter

Last updated