Skip to content
BytePatterns

Last Friend Standing in a Circle

MediumRecursion#recursion#josephus#recurrence~25m

Problem

n friends numbered 1 to n sit in a circle. Starting from friend 1, count k friends clockwise, counting the starting friend as 1; the friend you land on leaves the circle. The count starts again from the friend just after the one who left, and this repeats until one friend remains. Return that friend's number.

Examples

Input:  n = 5, k = 2
Output: 3
Why:    friends leave in the order 2, 4, 1, 5
Input:  n = 6, k = 5
Output: 1
Why:    friends leave in the order 5, 4, 6, 2, 3
Input:  n = 1, k = 7
Output: 1
Why:    edge case, a circle of one has its winner already

Hints

0 / 3

Stuck on the idea rather than the code? The Call Stack covers it.