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
Pass the Pillow: n=4, time=51234💤Person 1Person 2Person 3Person 4Movement sequence:t=0: Person 1 (start)t=1: Person 2 (forward)t=2: Person 3 (forward)t=3: Person 4 (forward, hit end)t=4: Person 3 (backward)t=5: Person 2 (backward) ✓Answer: Person 2
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
Asked in
Google 15 Amazon 12 Microsoft 8
31.2K Views
Medium Frequency
~15 min Avg. Time
890 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