FastPrepJosephus Survivor

Josephus Survivor

Apple logoApple● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

People numbered 1 through n stand in a circle in increasing order. Starting with person 1 as count one, count forward and remove the kth remaining person. Resume counting at one from the next remaining person, and repeat until one person remains.

Return the surviving person's original number. Counting wraps around the circle and includes only people still present.

Function

josephusSurvivor(n: int, k: int) → int

Examples

Example 1

n = 5k = 2return = 3

The removed people are 2,4,1,5; person 3 survives.

Example 2

n = 1k = 7return = 1

The only person is already the survivor.

Constraints

  • 1 <= n <= 10^5.
  • 1 <= k <= 10^9.

More Apple problems

See Apple hiring insights
public int josephusSurvivor(int n, int k) {
    // Write your solution here.
}
n5
k2
expected3
Checking account…