Engineering platform~10 min2s · 256 MBtarget O(n k) time, O(n) spacesorting
The issue tracker of a developer platform shows a banner with its oldest open tickets. Each ticket has an age in days. The banner has room for k tickets, and k is never more than 20.
You get the ages of all open tickets, in no particular order. The banner must list the k oldest ages, oldest first.
The team has a hand method: find the oldest ticket and move it to the front, then find the oldest among the rest, and repeat k times.
Write oldest_tickets(ages, k).
ages[i] is the age in days of ticket i.k is the number of ages to show, and k ≤ len(ages).k largest ages, largest first. Equal ages appear as many times as they occur.k is 0.Input: ages = [12, 40, 7, 40, 25], k = 2
Output: [40, 40]Each pass finds the oldest ticket among the places that are not yet fixed, and swaps it into the next place.
| Pass | Search from place | Oldest found at | List after the swap |
|---|---|---|---|
| 1 | 0 | place 1 (40) | [40, 12, 7, 40, 25] |
| 2 | 1 | place 3 (40) | [40, 40, 7, 12, 25] |
After 2 passes the first 2 places hold 40 and 40.
Input: ages = [5, 9, 1], k = 3
Output: [9, 5, 1]Three passes sort the whole list.
Input: ages = [3, 8], k = 0
Output: []The banner shows nothing, so no pass runs.
0 ≤ ages.length ≤ 100,000 (open tickets)0 ≤ ages[i] ≤ 100,000 (days)0 ≤ k ≤ 20, and k ≤ ages.lengthSorting the whole list with a hand method such as bubble sort costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. Because k is at most 20, k passes over the list cost at most 20 × n = 2 × 10^6 steps.