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 Java solution loops through each second to increment or decrement the position based on the direction. The direction changes each time a boundary (first or last person) is encountered.
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)
1#include <stdio.h>
2
3int passThePillow(int n, int time) {
4 int cycles = time / (n - 1);
5 int remainder = time % (n - 1);
6
7 if (cycles % 2 == 0) {
8 return 1 + remainder;
9 } else {
10 return n - remainder;
11 }
12}
13
14int main() {
15 int n = 4, time = 5;
16 printf("%d\n", passThePillow(n, time));
17 return 0;
18}
This C code calculates how many complete cycles of passing are done using time / (n - 1)
. Depending on whether the cycle count is even or odd, the remainder updates the position in forward or backward direction.