#3178
Find the Child Who Has the Ball After K Seconds
EasyMathSimulationSimulationMathematical Patterns
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(k) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of simulating each second, we can determine the effective position using the modulo operation. The ball's movement is periodic, so we can find the position after k seconds without simulating each second.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the effective time as k % (2 * (n - 1)).
- 2Step 2: Determine the position based on the effective time and the direction of movement.
- 3Step 3: If the effective time is less than n, return the effective time; otherwise, calculate the position from the end.
solution.py8 lines
1# Full working Python code
2
3def find_child(n, k):
4 effective_time = k % (2 * (n - 1))
5 if effective_time < n:
6 return effective_time
7 else:
8 return (2 * (n - 1)) - effective_timeℹ
Complexity note: The time complexity is O(1) because we perform a constant number of calculations, and the space complexity is O(1) since we only use a few variables.
- 1The ball's passing is periodic, which allows us to use modulo to simplify calculations.
- 2Understanding the direction change at the ends of the queue is crucial for determining the ball's position.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.