Pass the Pillow - Problem
There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.
For example, once the pillow reaches the nth person they pass it to the n - 1th person, then to the n - 2th person and so on.
Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.
Input & Output
Example 1 — Basic Case
$
Input:
n = 4, time = 5
›
Output:
2
💡 Note:
The pillow passes: 1→2→3→4→3→2. After 5 seconds, person 2 holds the pillow.
Example 2 — Single Person
$
Input:
n = 1, time = 3
›
Output:
1
💡 Note:
Only one person, so they always hold the pillow regardless of time.
Example 3 — Complete Cycle
$
Input:
n = 3, time = 4
›
Output:
1
💡 Note:
Pattern: 1→2→3→2→1. After 4 seconds, back to person 1.
Constraints
- 1 ≤ n ≤ 1000
- 0 ≤ time ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
n=4 people, time=5 seconds
2
Process
Pillow moves: 1→2→3→4→3→2
3
Output
Person 2 holds the pillow
Key Takeaway
🎯 Key Insight: The pillow follows a repeating back-and-forth cycle that can be calculated mathematically
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code