![]() |
VOOZH | about |
There are n people from 1 to n are standing in the queue at a movie ticket counter. It is a weird ticket counter, as it distributes tickets to the first k people and then the last k people, and again the first k people, and so on. Once a person gets a ticket, they move out of the queue. The task is to find the last person to get the ticket.
Examples:
Input: n = 9, k = 3
Output: 6
Explanation: Starting queue will like [1, 2, 3, 4, 5, 6, 7, 8, 9]. After the first distribution queue will look like [4, 5, 6, 7, 8, 9]. And after the second distribution queue will look like [4, 5, 6]. The last person to get the ticket will be 6.Input: n = 5, k = 1
Output: 3
Explanation: Queue starts as [1, 2, 3, 4, 5] -> [2, 3, 4, 5] -> [2, 3, 4] -> [3, 4] -> [3], Last person to get a ticket will be 3.
The given approach utilizes a deque (double-ended queue) data structure to simulate the ticket distribution process. The main idea is to pop elements from both ends of the queue in a specific pattern until only one person remains.
Follow the steps to solve the problem:
1. Iterate from i = 1 to n and add each person's number to the back of the deque using dq.push_back(i).
2. Perform the following steps until the size of the deque becomes 1:
3. Return the element at the front of the deque using dq.front(), which represents the last person to receive a ticket.
6
The given approach utilizes a two-pointer approach to find the last person to receive a ticket. It maintains two pointers, left and right, which represent the leftmost and rightmost positions in the queue, respectively.
Follow the steps to solve the problem:
1. Initialize left to 1 (representing the leftmost position in the queue) and right to n (representing the rightmost position in the queue).
2. Initialize firstDistribution to true, indicating the first distribution of tickets.
3. While the left is less than or equal to right, repeat the following steps:
4. If the while loop condition is not satisfied, return 0 as an error value.
6
The given approach uses a calculation-based approach to determine the last person to receive a ticket. It avoids explicitly simulating the distribution process and directly computes the result based on the values of n and k.
Follow the steps to solve the problem:
Perform the following checks in order to determine the last person to receive a ticket:
If none of the above conditions are satisfied, return an appropriate error value.
6
Time complexity: O(1), because the calculations and checks performed are constant time operations.
Auxiliaryspace: O(1), as there is constant space used.