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 - Optimal Solution INPUT n = 4 people in a line 1 Start 2 3 4 End Pillow n = 4 time = 5 seconds Cycle length = 2*(n-1) = 6 Pass Sequence: t=0: P1 --> t=1: P2 --> t=2: P3 t=3: P4 --> t=4: P3 --> t=5: P2 ALGORITHM STEPS 1 Calculate Cycle cycle = 2 * (n - 1) = 6 2 Get Position in Cycle pos = time % cycle = 5 % 6 = 5 3 Check Direction pos < n-1? No (5 > 3) Going backward! 4 Calculate Person result = cycle - pos + 1 = 6 - 5 + 1 = 2 Formula: if pos <= n-1: return pos + 1 else: return cycle - pos + 1 FINAL RESULT After 5 seconds: 1 2 3 4 Pillow Going backward Output: 2 OK - Person 2 holds the pillow Time: O(1) Space: O(1) Key Insight: The pillow movement is cyclic with period = 2*(n-1). For n=4, one full cycle takes 6 seconds. Use modulo to find position within cycle, then determine if moving forward (pos < n-1) or backward. This avoids simulating each second, achieving O(1) time complexity regardless of time value. TutorialsPoint - Pass the Pillow | Optimal Solution (Mathematical Approach)
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