#3178
Easy Algorithms Find the child who has the ball after k seconds
Math Simulation
62.0% acceptance
Feb 24, 2026
179
11
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, the direction of passing is reversed.
Return the number of the child who receives the ball after k seconds.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn number_of_child(n: i32, k: i32) -> i32 {
let period = 2 * (n - 1);
let pos = k % period;
if pos <= n - 1 {
pos
} else {
period - pos
}
}
}