Sponsored
Sponsored
This approach simulates the process of each person buying their tickets. We keep track of the time spent and decrement the ticket count from each person one at a time until the k-th person has purchased all their tickets.
Time Complexity: O(n * max(tickets)) where max(tickets) is the maximum tickets any person wants to buy.
Space Complexity: O(1)
1function timeToBuyTickets(tickets, k) {
2 let time = 0;
3 const n = tickets.length;
4 while (true) {
5 for (let i = 0; i < n; i++) {
6 if (tickets[i] > 0) {
7 tickets[i]--;
8 time++;
9 if (i === k && tickets[k] === 0) return time;
10 }
11 }
12 }
13}
14
15console.log(timeToBuyTickets([2, 3, 2], 2));
JavaScript leverages the dynamic nature of arrays and uses a tactical loop to decrement ticket counts and track the time until the k-th person is done buying.
This approach avoids the simulation by calculating the total time taken mathematically. For this, we traverse through each person and calculate the time based on the number of people in the queue and the minimum value between their current tickets and the tickets needed by k-th person.
Time Complexity: O(n)
Space Complexity: O(1)
1
This solution avoids direct simulation by calculating how many tickets each person can buy based on their position relative to k.