Sponsored
Sponsored
This approach involves simulating the process of passing the pillow using a loop. We start from the first person in the line and traverse it based on the time parameter. When we reach the end, we simply reverse the direction and continue until the given time is exhausted.
Time Complexity: O(time), since we simulate each passing of the pillow individually.
Space Complexity: O(1), as we only utilize a few integer variables for tracking state.
1
public class Program {
public static int PassThePillow(int n, int time) {
int position = 1;
int direction = 1;
for (int t = 0; t < time; ++t) {
position += direction;
if (position == n + 1) {
direction = -1;
position = n - 1;
} else if (position == 0) {
direction = 1;
position = 2;
}
}
return position;
}
public static void Main() {
int n = 4, time = 5;
Console.WriteLine(PassThePillow(n, time));
}
}
Solve with full IDE support and test cases
The C# program leverages a loop to manage the pillow's position, modifying its direction accordingly when the boundaries are reached.
This approach employs modulo arithmetic to determine the position of the pillow. By calculating the rounds of back-and-forth transfers based on time, we can derive the final position without directly simulating each second.
Time Complexity: O(1)
Space Complexity: O(1)
1public class Main {
2 public static int passThePillow(int n, int time) {
3 int cycles = time / (n - 1);
4 int remainder = time % (n - 1);
5
6 if (cycles % 2 == 0) {
7 return 1 + remainder;
8 } else {
9 return n - remainder;
10 }
11 }
12
13 public static void main(String[] args) {
14 int n = 4, time = 5;
15 System.out.println(passThePillow(n, time));
16 }
17}
This Java solution applies modular arithmetic to deduce the final position of the pillow, opting to calculate rather than simulate each sequential step.