Maps app~30 min2s · 256 MBtarget O(n log k) time, O(n) spacek-way-merge
You work on a maps app. A bus stop is served by several lines, and each line has a sorted list of departure times in seconds of the week. A traveller can take any line.
The app shows a "busy window": a short span of time in which at least need different lines depart. Your team lead asks: "What is the shortest such span?" The lists hold up to 200,000 times in all, and a stop can have thousands of lines.
Write smallest_covering_range(lists, need).
lists[i] is the sorted list of departure times of line i. A time can repeat inside a list. No list is empty.[a, b] covers a line when the line has a departure time t with a ≤ t ≤ b.need different lines and has the smallest length b - a. When several ranges have the smallest length, choose the one with the smallest a.[a, b].Input: lists = [[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30], [7, 11, 21]], need = 3
Output: [9, 11]The range 9 to 11 holds 9 (line 1), 10 (line 0) and 11 (line 3). The merged stream is (0, line 1), (4, line 0), (5, line 2), (7, line 3), (9, line 1), (10, line 0), (11, line 3), and so on.
| Right edge | Time and line | Lines inside | Shortest window found | Best so far |
|---|---|---|---|---|
| 0 | 0, line 1 | 1 | none | none |
| 1 | 4, line 0 | 2 | none | none |
| 2 | 5, line 2 | 3 | 0 to 5, length 5 | 0 to 5 |
| 3 | 7, line 3 | 3 | 4 to 7, length 3 | 4 to 7 |
| 4 | 9, line 1 | 3 | 5 to 9, length 4 | 4 to 7 |
| 5 | 10, line 0 | 3 | 7 to 10, length 3 | 4 to 7 |
| 6 | 11, line 3 | 3 | 9 to 11, length 2 | 9 to 11 |
Later windows have length 2 or more, and none of the length 2 has a smaller start than 9.
Input: lists = [[5, 5, 5]], need = 1
Output: [5, 5]One departure is enough, so the range is a single time.
Input: lists = [[1, 5], [3, 7]], need = 2
Output: [1, 3]The ranges 1 to 3, 3 to 5 and 5 to 7 all have length 2, and the smallest start is 1.
1 ≤ lists.length ≤ 5,000 (bus lines)1 ≤ lists[i].length, and all lists together hold at most 200,000 times0 ≤ lists[i][j] ≤ 604,800, and each list is sorted in non-decreasing order1 ≤ need ≤ lists.lengthTrying every time as the start of a range, and looking in every list for what the range needs, costs about 200,000 × 200,000 = 40,000,000,000 steps.
Merging the lists into one sorted stream costs about 200,000 × 13 = 2,600,000 steps with a heap. A window over the stream then moves two edges forward, with about 400,000 steps.