Pass the Pillow - Problem

Imagine n people standing in a line, numbered from 1 to n. The first person starts with a pillow and passes it down the line every second. But here's the twist: when the pillow reaches the end of the line, it bounces back and travels in the opposite direction!

Think of it like a pendulum swing - the pillow moves from person 1 → 2 → 3 → ... → n, then reverses direction: n → (n-1) → (n-2) → ... → 1, and continues this back-and-forth pattern.

Your task: Given the number of people n and the time elapsed time, determine which person is holding the pillow after time seconds.

Example: With 4 people, the sequence goes: 1 → 2 → 3 → 4 → 3 → 2 → 1 → 2 → ...

Input & Output

example_1.py — Basic Forward Movement
$ Input: n = 4, time = 2
Output: 3
💡 Note: At time 0: position 1. At time 1: position 2. At time 2: position 3. The pillow is moving forward and hasn't reached the end yet.
example_2.py — Direction Reversal
$ Input: n = 3, time = 4
Output: 2
💡 Note: Sequence: 1→2→3→2→1. At time 4, we've gone forward to position 3, then started moving backward: 3→2. So position is 2.
example_3.py — Complete Cycle
$ Input: n = 4, time = 6
Output: 1
💡 Note: One complete cycle takes 2(n-1) = 6 seconds: 1→2→3→4→3→2→1. After 6 seconds, we're back at the starting position.

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ time ≤ 1000
  • The pillow always starts at person 1
  • Time represents seconds elapsed, not the final timestamp

Visualization

Tap to expand
The Pillow's Cyclical Journey1234StartForward →← BackwardMathematical Pattern (n=4):• Cycle Length = 2(n-1) = 2(3) = 6 seconds• Forward Phase: positions 1→2→3→4 (3 steps)• Backward Phase: positions 4→3→2→1 (3 steps)• For any time t: position = f(t % 6)• This reduces O(time) to O(1) complexity!
Understanding the Visualization
1
Forward Phase
Pillow moves from position 1 to n (takes n-1 steps)
2
Backward Phase
Pillow moves from position n back to 1 (takes n-1 steps)
3
Complete Cycle
Total cycle time is 2(n-1) seconds
4
Mathematical Shortcut
Use time % cycle_length to skip repetitive simulation
Key Takeaway
🎯 Key Insight: The pillow's movement is cyclical with period 2(n-1). Instead of simulating each step, we can use modular arithmetic to instantly calculate the final position, achieving O(1) time complexity!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
23.5K Views
Medium Frequency
~15 min Avg. Time
892 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