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)
1def pass_the_pillow(n, time):
2 cycles = time // (n - 1)
3 remainder = time % (n - 1)
4
5 if cycles % 2 == 0:
6 return 1 + remainder
7 else:
8 return n - remainder
9
10n, time = 4, 5
11print(pass_the_pillow(n, time))
This Python function calculates the number of complete cycles and uses modulo arithmetic to determine the position, offering a clear and efficient solution.