Online store~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-950queues
An online store keeps a stack of banners for its home page. The page shows the banner on top and takes it off the stack. Then it moves the next banner from the top of the stack to the bottom. It repeats this until the stack is empty.
A marketer wants the banners to show in increasing order of their ids. You choose the order of the stack. A store can hold 300,000 banners, so trying orders one by one is out of the question.
Write carousel_order(ids).
ids lists distinct banner ids, in no particular order.Input: ids = [41, 12, 35, 8, 20, 27, 15]
Output: [8, 35, 12, 27, 15, 41, 20]Do not look for the ids: look for the positions. Run the procedure on the positions 0 to 6, in a queue. The position shown first gets the smallest id, the position shown second gets the next, and so on.
| Shown | Position shown | Queue after removing it | Queue after moving the next one to the bottom |
|---|---|---|---|
| 1st, id 8 | 0 | 1, 2, 3, 4, 5, 6 | 2, 3, 4, 5, 6, 1 |
| 2nd, id 12 | 2 | 3, 4, 5, 6, 1 | 4, 5, 6, 1, 3 |
| 3rd, id 15 | 4 | 5, 6, 1, 3 | 6, 1, 3, 5 |
| 4th, id 20 | 6 | 1, 3, 5 | 3, 5, 1 |
| 5th, id 27 | 3 | 5, 1 | 1, 5 |
| 6th, id 35 | 1 | 5 | 5 |
| 7th, id 41 | 5 | empty | empty |
So the stack, top first, is 8, 35, 12, 27, 15, 41, 20.
Input: ids = [4, 9]
Output: [4, 9]Two banners: 4 is shown from the top, then 9 is moved to the bottom of an empty stack and shown.
Input: ids = [8]
Output: [8]One banner.
1 ≤ length of ids ≤ 3 × 10^51 ≤ ids[i] ≤ 10^7, and all ids are differentThere are n! stacks to try, which is far too many for even n = 20. Building the stack backwards with inserts at the front of a list costs up to n steps for each insert, and each id needs two inserts. That is about n × n moves, or 9 × 10^10 for n = 300,000.
Sorting costs O(n log n). Acting out the procedure on positions with a queue costs O(n). So the whole run is O(n log n), and ids fit in an int.