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
Solve with full IDE support and test cases
This C solution simulates the passage of the pillow by updating the position with a direction variable to track when the end of the line is reached. Once the last person receives the pillow, the direction is inverted. This continues until 'time' iterations are exhausted.
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)
1using System;
2
3public class Program {
4 public static int PassThePillow(int n, int time) {
5 int cycles = time / (n - 1);
6 int remainder = time % (n - 1);
7
8 if (cycles % 2 == 0) {
9 return 1 + remainder;
10 } else {
11 return n - remainder;
12 }
13 }
14
15 public static void Main() {
16 int n = 4, time = 5;
17 Console.WriteLine(PassThePillow(n, time));
18 }
19}
The C# solution determines cycles and uses their parity to calculate the final position efficiently, foregoing the overhead of simulation.