KatInterview

Token Hop Around a Ring

Math & Bit ManipulationAuto-graded · 20 test cases
EasyAuto-gradedMath & Bit Manipulationmathmodular-arithmeticsimulation

Last 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

  • n is a positive integer (n >= 1).
  • k is a non-negative integer, and may be far larger than n; a hop-by-hop simulation may be too slow for the largest values.
  • The function returns a single integer in the range 0 to n - 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.