Problem
You are given two positive integers n
and k
. There are n
children numbered from 0
to n - 1
standing in a queue in order from left to right.
Initially, child 0 holds a ball and the direction of passing the ball is towards the right direction. After each second, the child holding the ball passes it to the child next to them. Once the ball reaches either end of the line, i.e. child 0 or child n - 1
, the direction of passing is
reversed.
Return the number of the child who receives the ball after k
seconds.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
2 <= n <= 50
1 <= k <= 50
Note: This question is the same as 2582: Pass the Pillow.
Solution
Method 1 – Simulation with Modulo Arithmetic
Intuition
The ball moves back and forth between the ends. The movement forms a cycle of length 2 * (n - 1)
. We can use modulo arithmetic to find the position after k seconds efficiently.
Approach
- Compute the cycle length as
2 * (n - 1)
. - The effective time is
k % cycle
. - If the effective time is less than
n
, the ball is moving right, so the answer iseffective time
. - Otherwise, the ball is moving left, so the answer is
cycle - effective time
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, as only arithmetic operations are used. - 🧺 Space complexity:
O(1)
, as only a few variables are used.