Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

The Josephus Problem

n people, numbered from 0 to n - 1, stand in a circle. Starting at person 0 and counting around the circle, every k-th person is eliminated; counting continues from the next surviving person after each elimination. This repeats until only one person remains. Return the (zero-indexed) position of that survivor in the original circle.

Example 1

Input: n = 5, k = 2
Output: 2
Explanation: Eliminate 1, 3, 0, 4 in that order (counting every
2nd surviving person starting from 0). Person 2 survives.

Example 2

Input: n = 1, k = 1
Output: 0
Explanation: With only one person, they trivially survive.

Constraints

  • 1 <= n <= 5 * 10^4
  • 1 <= k <= 2 * 10^9

Share this question

← Back to Math and Geometry practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.