Find the Child Who Has the Ball After K Seconds - 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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 5
Output: 1
💡 Note: Ball moves: 0→1→2→1→0→1. After 5 seconds, ball is at position 1.
Example 2 — Reaches End
$ Input: n = 5, k = 6
Output: 2
💡 Note: Ball moves: 0→1→2→3→4→3→2. After 6 seconds, ball is at position 2.
Example 3 — Single Child
$ Input: n = 1, k = 10
Output: 0
💡 Note: Only one child, so ball always stays at position 0.

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ k ≤ 50

Visualization

Tap to expand
Find the Child Who Has the Ball After K Seconds INPUT n = 3 children in a queue 0 Ball 1 2 Initial direction: RIGHT n = 3 k = 5 seconds Find child with ball after k sec Ball bounces at ends 0 --> 1 --> 2 --> 1 --> 0 --> 1 s0 s1 s2 s3 s4 s5 Reverses at child 0 and n-1 ALGORITHM STEPS 1 Find Cycle Length cycle = 2 * (n - 1) = 4 2 Get Position in Cycle pos = k % cycle = 5 % 4 = 1 3 Check Direction if pos < n-1: going right else: going left (bounce) 4 Calculate Child pos=1 < n-1=2: return pos Answer = 1 Cycle Pattern (n=3) Position: 0 1 2 1 0 1 Time: 0 1 2 3 4 5 |--cycle=4--| 5 mod 4 = 1 --> position 1 FINAL RESULT After 5 seconds: 0 1 Has Ball! 2 Output: 1 Child 1 receives the ball after 5 seconds Trace: 0-->1-->2-->1-->0-->1 OK - Verified! Key Insight: The ball movement follows a predictable cycle of length 2*(n-1). Instead of simulating k seconds, use modulo arithmetic: pos = k % (2*(n-1)). If pos < n-1, the answer is pos (moving right); otherwise it's 2*(n-1) - pos (bounced back). Time: O(1), Space: O(1). TutorialsPoint - Find the Child Who Has the Ball After K Seconds | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
30.3K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen