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.
1using namespace std;
int passThePillow(int n, int time) {
int position = 1, direction = 1;
for (int i = 0; i < time; ++i) {
position += direction;
if (position == 0) {
position = 2;
direction = 1;
} else if (position == n + 1) {
position = n - 1;
direction = -1;
}
}
return position;
}
int main() {
int n = 4, time = 5;
cout << passThePillow(n, time) << endl;
return 0;
}
Solve with full IDE support and test cases
This C++ implementation is similar to the C version, iterating through each second to update the position of the pillow. When the edge of the array is reached, it changes directions.
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.