Leetcode 2582. Pass the Pillow
Alice and Bob play a game with a pillow. Initially, Alice has the pillow. They pass the pillow to the next person every second.
Given two integers n
(the number of people in the circle) and time
, return the index of the person who has the pillow after time
seconds.
The people in the circle are indexed from 1 to n.
Example 1:
Input: n = 4, time = 5
Output: 2
Explanation:
Alice starts with the pillow at time 0.
After 1 second, Alice passes the pillow to Bob.
After 2 seconds, Bob passes the pillow to the 3rd person.
After 3 seconds, the 3rd person passes the pillow to the 4th person.
After 4 seconds, the 4th person passes the pillow to Alice.
After 5 seconds, Alice passes the pillow to Bob.
Example 2:
Input: n = 3, time = 2
Output: 3
Explanation:
Alice starts with the pillow at time 0.
After 1 second, Alice passes the pillow to Bob.
After 2 seconds, Bob passes the pillow to the 3rd person.
n
be as small as 1?
n >= 2
.n
and time
?
time
within an n
-person circle, the problem translates to a modulo operation. Essentially, after every n
seconds, the sequence restarts.((time - 1) % n) + 1
.Here’s the implementation:
public class PillowGame {
public int passThePillow(int n, int time) {
return ((time - 1) % n) + 1;
}
public static void main(String[] args) {
PillowGame pg = new PillowGame();
System.out.println(pg.passThePillow(4, 5)); // Output: 2
System.out.println(pg.passThePillow(3, 2)); // Output: 3
}
}
The time complexity of this solution is constant, O(1), because:
The space complexity is also O(1) since we are not using any additional space that scales with input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?