Bank app~20 min2s · 256 MBtarget O(n) time, O(n) spacequeues
A bank branch hands out numbered tickets, and a clerk calls them in the order they were given. Some customers need a document check. Their ticket is shown as a negative number.
The first time the clerk calls such a ticket, the customer joins the back of the line. From then on the ticket counts as plain. A branch can hand out 300,000 tickets in a day, and the clerk wants the order in which tickets are closed.
Write closing_order(tickets).
tickets lists the tickets in the order they joined the line. A ticket number is a whole number that is not 0.-t is not closed the first time it is called: it goes to the back of the line as the plain ticket t.Input: tickets = [7, -4, 9, -2, 5]
Output: [7, 9, 5, 4, 2]A queue acts out the line. The clerk takes the front ticket. A plain ticket is closed. A negative ticket goes to the back as a plain ticket.
| Call | Line after the call | Closed so far |
|---|---|---|
| 7 | -4, 9, -2, 5 | 7 |
| -4 | 9, -2, 5, 4 | 7 |
| 9 | -2, 5, 4 | 7, 9 |
| -2 | 5, 4, 2 | 7, 9 |
| 5 | 4, 2 | 7, 9, 5 |
| 4 | 2 | 7, 9, 5, 4 |
| 2 | empty | 7, 9, 5, 4, 2 |
Input: tickets = [3, 8]
Output: [3, 8]No ticket needs a check, so the tickets close in the order they came.
Input: tickets = [-6]
Output: [6]The only ticket goes to the back of an empty line, and is called again at once.
1 ≤ length of tickets ≤ 3 × 10^5-10^6 ≤ tickets[i] ≤ 10^6, and no ticket is 0Taking the front of a plain list shifts every ticket behind it, which costs up to n steps for each call. A branch with n = 300,000 tickets would make about 4.5 × 10^10 shifts in all.
A queue gives the front and the back in O(1). Each ticket is called at most twice, so the whole run costs about 2n queue steps. Ticket numbers fit in an int.