Music streaming app~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-315sorting
A music app logs each listening session with its length in seconds. The sessions are in the order they ended. For each session, the analytics team wants to know how many sessions that ended later were shorter.
A session with a high count was long compared with what followed it. A session with a count of 0 was no longer than anything that came after.
Write count_shorter_later(lengths).
lengths[i] is the length of the i-th session to end. Lengths can repeat.i, count the positions j > i with lengths[j] < lengths[i].lengths.Input: lengths = [5, 2, 6, 1]
Output: [2, 1, 1, 0]The first session, 5, has two shorter sessions after it: 2 and 1. Merge sort finds the counts while merging. The table shows the last merge, of the sorted halves [2, 5] and [1, 6]. Inside the halves, the 5 already gained 1 from the 2, and the 6 gained 1 from the 1.
| Step | Left waiting | Right waiting | Taken | Counts added |
|---|---|---|---|---|
| 1 | [2, 5] | [1, 6] | 1 from the right | none |
| 2 | [2, 5] | [6] | 2 from the left | 2 gains 1 |
| 3 | [5] | [6] | 5 from the left | 5 gains 1 |
| 4 | [] | [6] | 6 from the right | none |
The 5 ends with 1 + 1 = 2, the 2 with 1, the 6 with 1, and the 1 with 0.
Input: lengths = [4, 4, 4]
Output: [0, 0, 0]Equal lengths are not shorter.
Input: lengths = [9, 7, 5, 3]
Output: [3, 2, 1, 0]Every later session is shorter.
0 ≤ lengths.length ≤ 100,000 (sessions)0 ≤ lengths[i] ≤ 1,000,000 (seconds)Checking every pair costs about n × n / 2, which is 5 × 10^9 at n = 100,000. Merge sort costs about n log n, roughly 1.7 million steps. Each count is at most n − 1, so a 32-bit integer is enough for one count.