Skip to content

2582. Pass the Pillow 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int passThePillow(int n, int time) {
    // Repeat every (n - 1) * 2 seconds.
    time %= (n - 1) * 2;
    if (time < n)  // Go forward from 1.
      return 1 + time;
    return n - (time - (n - 1));  // Go backward from n.
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int passThePillow(int n, int time) {
    // Repeat every (n - 1) * 2 seconds.
    time %= (n - 1) * 2;
    if (time < n) // Go forward from 1.
      return 1 + time;
    return n - (time - (n - 1)); // Go backward from n.
  }
}
1
2
3
4
5
6
7
class Solution:
  def passThePillow(self, n: int, time: int) -> int:
    # Repeat every (n - 1) * 2 seconds.
    time %= (n - 1) * 2
    if time < n:  # Go forward from 1.
      return 1 + time
    return n - (time - (n - 1))  # Go backward from n.