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
nthperson they pass it to then - 1thperson, then to then - 2thperson and so on.
Given the two positive integers n and time, return the index of the person holding the pillow aftertime seconds.
Examples
Example 1
Input: n = 4, time = 5
Output: 2
Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2nd person is holding the pillow.
Example 2
Input: n = 3, time = 2
Output: 3
Explanation: People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3rd person is holding the pillow.
Constraints
2 <= n <= 10001 <= time <= 1000
Note: This question is the same as [ 3178: Find the Child Who Has the Ball After K Seconds.](https://leetcode.com/problems/find-the-child-who-has-the- ball-after-k-seconds/description/)
Solution
Method 1 - Math (Simulation of Cycles)
Intuition
The pillow moves from 1 to n, then reverses from n to 1, and so on. Each full cycle (forward and backward) takes 2 * (n - 1) seconds. We can use modulo arithmetic to find the position after time seconds without simulating every step.
Approach
- Compute
cycle = 2 * (n - 1). - The effective time is
t = time % cycle. - If
t < n - 1, the pillow is moving forward: position is1 + t. - Otherwise, it's moving backward: position is
n - (t - (n - 1)).
Code
C++
int passThePillow(int n, int time) {
int cycle = 2 * (n - 1);
int t = time % cycle;
if (t < n - 1) return 1 + t;
else return n - (t - (n - 1));
}
Go
func passThePillow(n int, time int) int {
cycle := 2 * (n - 1)
t := time % cycle
if t < n-1 {
return 1 + t
}
return n - (t - (n - 1))
}
Java
class Solution {
public int passThePillow(int n, int time) {
int cycle = 2 * (n - 1);
int t = time % cycle;
if (t < n - 1) return 1 + t;
else return n - (t - (n - 1));
}
}
Kotlin
fun passThePillow(n: Int, time: Int): Int {
val cycle = 2 * (n - 1)
val t = time % cycle
return if (t < n - 1) 1 + t else n - (t - (n - 1))
}
Python
def passThePillow(n: int, time: int) -> int:
cycle = 2 * (n - 1)
t = time % cycle
if t < n - 1:
return 1 + t
else:
return n - (t - (n - 1))
Rust
pub fn pass_the_pillow(n: i32, time: i32) -> i32 {
let cycle = 2 * (n - 1);
let t = time % cycle;
if t < n - 1 {
1 + t
} else {
n - (t - (n - 1))
}
}
TypeScript
function passThePillow(n: number, time: number): number {
const cycle = 2 * (n - 1);
const t = time % cycle;
if (t < n - 1) return 1 + t;
return n - (t - (n - 1));
}
Complexity
- ⏰ Time complexity:
O(1)(constant time, no loops). - 🧺 Space complexity:
O(1)(no extra space).
published: true