Music streaming app~20 min2s · 256 MBtarget O(n + k) time, O(n + k) spacesorting
A streaming app groups viewing sessions into length buckets of 15 minutes: 0 to 14, 15 to 29, 30 to 44, and so on. The report lists the sessions bucket by bucket, shortest bucket first. Inside a bucket the sessions stay in the order they started. Each session is known by its index in the day's list.
Write order_sessions_by_bucket(lengths).
lengths[i] is the length of session i in whole minutes.lengths[i] // 15, rounded down.Input: lengths = [32, 5, 47, 18, 30, 3]
Output: [1, 5, 3, 0, 4, 2]Put each session in its bucket, then list the buckets from the lowest. Sessions inside a bucket stay in index order.
| Bucket | Minutes | Sessions in it | Starts at place |
|---|---|---|---|
| 0 | 0 to 14 | 1, 5 | 0 |
| 1 | 15 to 29 | 3 | 2 |
| 2 | 30 to 44 | 0, 4 | 3 |
| 3 | 45 to 59 | 2 | 5 |
Reading the last column in order gives [1, 5, 3, 0, 4, 2].
Input: lengths = [20, 25, 29]
Output: [0, 1, 2]All three sessions are in bucket 1, so they keep their order: [0, 1, 2].
Input: lengths = [15, 14]
Output: [1, 0]The length 15 starts bucket 1, and 14 ends bucket 0, so the second session comes first: [1, 0].
0 ≤ lengths.length ≤ 100,000 (sessions)0 ≤ lengths[i] ≤ 600 (minutes), so there are 41 buckets, numbered 0 to 40.There are only 41 buckets. Counting how many sessions fall in each bucket costs n, and placing each session costs n, so the whole job is linear and keeps the order.