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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code