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 aftertimeseconds.
Input: n =4, time =5Output: 2Explanation: People pass the pillow in the following way:1->2->3->4->3->2.After five seconds, the 2nd person is holding the pillow.
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.
classSolution {
publicintpassThePillow(int n, int time) {
int cycle = 2 * (n - 1);
int t = time % cycle;
if (t < n - 1) return 1 + t;
elsereturn n - (t - (n - 1));
}
}
1
2
3
4
5
funpassThePillow(n: Int, time: Int): Int {
val cycle = 2 * (n - 1)
val t = time % cycle
returnif (t < n - 1) 1 + t else n - (t - (n - 1))
}
1
2
3
4
5
6
7
defpassThePillow(n: int, time: int) -> int:
cycle =2* (n -1)
t = time % cycle
if t < n -1:
return1+ t
else:
return n - (t - (n -1))
1
2
3
4
5
6
7
8
9
pubfnpass_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))
}
}