Find the Child Who Has the Ball After K Seconds
EasyPrompt
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.
Example 1:
Input: n = 3, k = 5
Output: 1
Explanation:
| Time elapsed | Children |
|---|---|
0 |
[0, 1, 2] |
1 |
[0, 1, 2] |
2 |
[0, 1, 2] |
3 |
[0, 1, 2] |
4 |
[0, 1, 2] |
5 |
[0, 1, 2] |
Example 2:
Input: n = 5, k = 6
Output: 2
Explanation:
| Time elapsed | Children |
|---|---|
0 |
[0, 1, 2, 3, 4] |
1 |
[0, 1, 2, 3, 4] |
2 |
[0, 1, 2, 3, 4] |
3 |
[0, 1, 2, 3, 4] |
4 |
[0, 1, 2, 3, 4] |
5 |
[0, 1, 2, 3, 4] |
6 |
[0, 1, 2, 3, 4] |
Example 3:
Input: n = 4, k = 2
Output: 2
Explanation:
| Time elapsed | Children |
|---|---|
0 |
[0, 1, 2, 3] |
1 |
[0, 1, 2, 3] |
2 |
[0, 1, 2, 3] |
Constraints:
2 <= n <= 501 <= k <= 50
Note: This question is the same as 2582: Pass the Pillow.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach mimics the ball-passing process step-by-step. We keep track of the ball's current position and its direction of movement. By iterating k times, we simulate each second of the process, updating the ball's location and reversing its direction when it reaches either end of the line. This method is intuitive and easy to follow, directly translating the problem's description into code.
Algorithm
- Initialize
currentChild = 0anddirection = 1(1 for right, -1 for left). - Loop
ktimes to simulatekpasses of the ball. - In each iteration, update the position by one step:
currentChild += direction. - After updating, check if the new position is an endpoint (
0orn-1). - If it is, reverse the direction for the next pass:
direction *= -1. - After the loop completes, return the final
currentChild.
Walkthrough
We can solve this problem by simulating the movement of the ball for k seconds.
- We'll use a variable
currentChildto track the index of the child with the ball, starting at0. - Another variable,
direction, will keep track of the movement direction (1for right,-1for left), starting at1. - We then loop
ktimes. In each iteration, representing one pass:- We update
currentChildby adding thedirection. This simulates the pass. - After the pass, we check if the ball has landed on an endpoint (
0orn-1). - If it has, we reverse the
directionfor the subsequent passes by multiplying it by-1.
- We update
After k iterations, the value of currentChild is the final answer.
class Solution { public int findTheChild(int n, int k) { int currentChild = 0; int direction = 1; // 1 for right, -1 for left for (int time = 0; time < k; time++) { currentChild += direction; if (currentChild == 0 || currentChild == n - 1) { direction *= -1; } } return currentChild; }}Complexity
Time
O(k) - The main part of the algorithm is a loop that runs `k` times, with constant time operations inside each iteration.
Space
O(1) - The algorithm uses a fixed number of variables (`currentChild`, `direction`, `time`), regardless of the input size.
Trade-offs
Pros
Simple to understand and implement.
Works correctly for the given problem constraints.
Cons
Inefficient for very large values of
k, as its runtime is directly proportional tok.
This highly efficient approach avoids simulation by using mathematical properties of the ball's movement. The ball's path is periodic. A full round trip from child 0 to n-1 and back to 0 takes a fixed number of steps. By calculating the total time for one cycle, we can use the modulo operator to find where in the cycle the ball will be after k seconds. This allows for a direct calculation of the final position in constant time.
Algorithm
- Calculate the time for one full round trip (from
0ton-1and back to0):period = 2 * (n - 1). - Calculate the effective time within a single cycle using the modulo operator:
effectiveTime = k % period. - Determine if the ball is in the forward or backward part of its journey:
- If
effectiveTime <= n - 1, the ball is moving from left to right. Its position iseffectiveTime. - If
effectiveTime > n - 1, the ball is moving from right to left. Its position is(n - 1) - (effectiveTime - (n - 1)).
- If
- Return the calculated position.
Walkthrough
The movement of the ball is cyclical. It travels from child 0 to n-1 (which takes n-1 seconds) and then back from n-1 to 0 (which also takes n-1 seconds).
- A complete round trip, therefore, takes
(n-1) + (n-1) = 2 * (n-1)seconds. - We can determine the final position by figuring out where in this cycle the
k-th second falls. The length of one full cycle isperiod = 2 * (n - 1). - We can find the effective time within a single cycle using the modulo operator:
effectiveTime = k % period. - Now, we analyze the position based on
effectiveTime:- Forward Pass: If
effectiveTimeis less than or equal ton-1, the ball is still on its way from0ton-1. In this case, its position is simplyeffectiveTime. - Backward Pass: If
effectiveTimeis greater thann-1, the ball has reached childn-1and is on its way back. It reachedn-1at timen-1(within the cycle) and has been moving back foreffectiveTime - (n-1)seconds. So, its position is(n-1) - (effectiveTime - (n-1)).
- Forward Pass: If
class Solution { public int findTheChild(int n, int k) { // The time for a full round trip (0 -> n-1 -> 0) is 2 * (n - 1) seconds. int period = 2 * (n - 1); // We only need to consider the position within the last, incomplete round trip. int effectiveTime = k % period; // If the effective time is less than or equal to the time to reach the end (n - 1), // the ball is moving forward from 0. The position is equal to the time elapsed. if (effectiveTime <= n - 1) { return effectiveTime; } else { // Otherwise, the ball is moving backward from n - 1. // It reached n-1 at time (n-1) and is now moving back. // The number of steps back from n-1 is (effectiveTime - (n-1)). return (n - 1) - (effectiveTime - (n - 1)); } }}Complexity
Time
O(1) - The solution consists of a few arithmetic calculations that are independent of the input values `n` and `k`.
Space
O(1) - The algorithm uses a constant amount of extra space for variables.
Trade-offs
Pros
Extremely efficient with a constant time complexity, making it suitable for very large
k.Elegant solution that demonstrates understanding of the problem's underlying pattern.
Cons
Slightly more complex to derive the logic compared to a straightforward simulation.
Solutions
Solution
class Solution {public int numberOfChild(int n, int k) { int mod = k % (n - 1); k /= (n - 1); return k % 2 == 1 ? n - mod - 1 : mod; }}class Solution {public: int numberOfChild(int n, int k) { int mod = k % (n - 1); k /= (n - 1); return k % 2 == 1 ? n - mod - 1 : mod; }};class Solution: def numberOfChild(self, n: int, k: int) -> int: k, mod = divmod(k, n - 1) return n - mod - 1 if k & 1 else modVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.