The Find the Child Who Has the Ball After K Seconds interview question is a cyclic simulation problem. children (indexed 0 to ) stand in a line. A ball starts at child 0 and moves to the right. When it reaches the end of the line (child ), it reverses direction and moves left. This continue until seconds have passed. You need to identify which child holds the ball at exactly seconds.
Meta and Google ask the Find the Child Who Has the Ball After K Seconds coding problem to test a candidate's ability to avoid brute-force simulation. While you could simulate steps, for very large , this is inefficient. It evaluates your knowledge of Math interview patterns, specifically modulo arithmetic and periodic sequences.
This problem uses Modulo Arithmetic based on the "Round Trip" period.
k_eff = k % (2 * (n - 1)).k_eff < n, the ball is moving to the right. The position is k_eff.k_eff >= n, the ball has reversed. The position is (2 * (n - 1)) - k_eff..
Always look for a "mathematical shortcut" in simulation problems involving repeated movements. If the movement is periodic, use the modulo operator to find the final state instantly. This is a core part of the Math interview pattern.