Payments app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-31traversal
The test harness of a payments app replays a queue of payout requests in every possible order, one after the other, in dictionary order of the priority numbers. Equal priorities are allowed.
Given the order that was replayed last, the harness must produce the next one. After the last order, it starts again from the first. The harness has memory for the queue only, so it changes the queue itself.
Write next_arrangement(queue).
queue[i] is the priority number of the i-th request.queue in place.queue is already the last arrangement, return the first one, with the numbers in ascending order.Input: queue = [2, 3, 6, 5, 4]
Output: [2, 4, 3, 5, 6]Find the last place where the order rises, swap it with the smallest larger entry to its right, and reverse the tail.
| Step | What you do | Queue after the step |
|---|---|---|
| 1 | the last rise is at place 1 (3 before 6) | [2, 3, 6, 5, 4] |
| 2 | swap 3 with the 4, the smallest larger entry on its right | [2, 4, 6, 5, 3] |
| 3 | reverse the tail after place 1 | [2, 4, 3, 5, 6] |
The tail 6, 5, 3 was the largest order of its entries, and it becomes the smallest.
Input: queue = [3, 2, 1]
Output: [1, 2, 3]No place rises, so this is the last arrangement, and the first one follows.
Input: queue = [1, 1, 5]
Output: [1, 5, 1]The last rise is at place 1 (1 before 5). Swapping gives [1, 5, 1], and the tail has one entry.
1 ≤ queue.length ≤ 100,000 (payout requests)1 ≤ queue[i] ≤ 1,000,000,000 (priority numbers)There can be up to 100,000! arrangements, so no search through them can work. The next arrangement shares the longest possible front with the current one, and that front can be found by reading from the back once, in about n steps.