#2582
Pass the Pillow
EasyMathSimulationSimulationMathematical Patterns
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of simulating each second, we can calculate the final position directly using the properties of the movement. The pillow moves back and forth, creating a predictable pattern based on the total time and the number of people.
⚙️
Algorithm
2 steps- 1Step 1: Calculate the effective time as time % (2 * (n - 1)) to account for complete back-and-forth cycles.
- 2Step 2: Determine the position based on the effective time: if it's less than n, the pillow is moving forward; otherwise, it's moving backward.
solution.py6 lines
1n, time = 4, 5
2effective_time = time % (2 * (n - 1))
3if effective_time < n:
4 print(effective_time + 1)
5else:
6 print(2 * n - effective_time - 1)ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the input size. The space complexity is also O(1) as we are using a fixed amount of extra space.
- 1The pillow's movement creates a repeating pattern that can be leveraged to calculate positions directly.
- 2Understanding the modulo operation helps in reducing unnecessary iterations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.