Token Hop Around a Ring
Math & Bit ManipulationAuto-graded · 20 test casesLast updated
Compute where a token lands on a ring after k escalating hops, which tests spotting a prefix-sum closed form with modular arithmetic instead of simulating.
n players sit around a ring, numbered 0 through n - 1 in clockwise order. A token starts with player 0.
The token is then moved in a series of hops. On hop number i (counting from i = 1), the current holder hands the token to the player located exactly i seats clockwise from them. The ring wraps around, so moving clockwise from player n - 1 leads back to player 0.
Given the number of players n and the number of hops k, return the index of the player holding the token after exactly k hops have been made.
If k is 0, no hops occur and the token remains with player 0. If n is 1, the answer is always 0.
Constraints
nis a positive integer (n >= 1).kis a non-negative integer, and may be far larger thann; a hop-by-hop simulation may be too slow for the largest values.- The function returns a single integer in the range
0ton - 1.
Examples
Example 1
Input: token_hop_holder(5, 2)
Output: 3
Example 2
Input: token_hop_holder(3, 3)
Output: 0
Hints
Hint 1
Write down the token's position, ignoring wrap-around, after hop 1, hop 2, hop 3. What pattern appears?
Hint 2
Without wrapping, the position after k hops is 1 + 2 + ... + k. Reducing modulo n at the very end gives the same result as reducing after every hop.
Hint 3
Use the formula k * (k + 1) / 2. The product of two consecutive integers is always even, so integer division is exact.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let p_i be the holder after hop i, with p_0 = 0. The rule is p_i = (p_{i-1} + i) mod n.
Since modular reduction is compatible with addition, we do not need to reduce after each hop. Unrolling the recurrence gives:
p_k = (1 + 2 + ... + k) mod n = (k * (k + 1) / 2) mod n
The product k * (k + 1) is a product of two consecutive integers, so it is always even and integer division by 2 is exact.
Why it is correct
- Each hop adds
ito the position, and the ring wrap-around is just reduction modulon. (a + b) mod n = ((a mod n) + b) mod n, so reducing once at the end gives the same answer as reducing at every step.n = 1gives0automatically, andk = 0gives0since the sum is empty.- Check:
n = 5, k = 2gives3 mod 5 = 3.n = 3, k = 3gives6 mod 3 = 0.
Complexity
- Time: O(1) arithmetic operations (big-integer multiplication costs O(log k) bit operations).
- Space: O(1).
In languages with fixed-width integers, k * (k + 1) can overflow for large k. Halve whichever of k and k + 1 is even first, reduce both factors mod n, then multiply and reduce again.
Reference solution
def token_hop_holder(n: int, k: int) -> int:
return (k * (k + 1) // 2) % n