Maps app~22 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · greedy
You work on a navigation app. A route is length kilometres long, and its kilometres are numbered from 1. Before a trip, the app can download offline map regions. Each region covers a stretch of whole kilometres.
Your team lead asks: "What is the fewest regions that cover every kilometre of the route?" A region can start before the route or end after it. The catalogue can hold 100,000 regions.
Write fewest_regions(starts, ends, length).
i covers the kilometres from starts[i] to ends[i], both included. Here starts[i] ≤ ends[i].length is covered.-1 when some kilometre cannot be covered.Input: starts = [1, 4, 3, 9, 6, 2], ends = [5, 8, 6, 12, 10, 3], length = 12
Output: 3Sort the regions by their start. Keep the end of the covered part. Among the regions that begin at or before the next uncovered kilometre, take the one that reaches the furthest.
| Pick | Covered up to | Regions that begin by the next kilometre | Furthest end |
|---|---|---|---|
| 1 | 0 | 1-5 | 5 |
| 2 | 5 | 2-3, 3-6, 4-8, 6-10 | 10 |
| 3 | 10 | 9-12 | 12 |
3 regions cover the route.
Input: starts = [1, 5], ends = [3, 8], length = 8
Output: -1Kilometre 4 is covered by neither region, so the answer is -1.
Input: starts = [1, 2], ends = [4, 6], length = 6
Output: 2The region 1-4 and the region 2-6 together cover the route. The region 2-6 alone leaves kilometre 1, so two regions are needed.
1 ≤ len(starts) = len(ends) ≤ 100,0001 ≤ starts[i] ≤ ends[i] ≤ 1,000,0001 ≤ length ≤ 1,000,000Trying every group of regions means 2^100,000 groups. Even trying every region at every step of a search is slow if the search can backtrack. A sort costs about 1.7 million steps, and a single sweep over the sorted regions then picks each region once.