Maps app~30 min2s · 256 MBtarget O(q log n) on average, O(q n) in the worst case time, O(1) spaceclassic twin: lc-154binary-search
A maps app prints the departures of a night bus network as minutes since midnight. The printout starts at the first bus after the evening, so it runs past midnight, and the minutes then restart from a small number. Many buses leave in the same minute.
The app shows the printout one page at a time. A page is a run of neighbouring departures. For each page, which minute is the earliest of the day?
Write earliest_per_page(minutes, pages).
minutes is a list in increasing order that was rotated: the first part moved to the end. It can hold equal minutes, and a rotation of 0 is allowed.[l, r] covers the slots l to r, both included.minutes[l] to minutes[r].Input: minutes = [1190, 1190, 1250, 1380, 30, 30, 75, 75, 120], pages = [[0, 8], [0, 3], [4, 8], [1, 5], [2, 2], [3, 6]]
Output: [30, 1190, 30, 30, 1250, 30]Take the page [1, 5]: the minutes 1190, 1250, 1380, 30, 30. The page starts with 1190 and ends with 30, so the last minute differs from the first and nothing is dropped. The search keeps a window [lo, hi) and compares the middle with the last minute.
| Step | lo | hi | mid | minutes[mid] | Last minute | Decision |
|---|---|---|---|---|---|---|
| 1 | 1 | 6 | 3 | 1380 | 30 | 1380 > 30, so lo = 4 |
| 2 | 4 | 6 | 5 | 30 | 30 | 30 is not above 30, so hi = 5 |
| 3 | 4 | 5 | 4 | 30 | 30 | 30 is not above 30, so hi = 4 |
| end | 4 | 4 | the smallest minute is minutes[4] = 30 |
The whole printout, page [0, 8], gives 30. The page [0, 3] is sorted, so its earliest minute is the first one, 1190. The page [4, 8] gives 30, the page [2, 2] is one slot, and the page [3, 6] gives 30.
Input: minutes = [5, 5, 5, 2, 5], pages = [[0, 4], [0, 2], [3, 4]]
Output: [2, 5, 2]The page [0, 4] starts and ends with 5, so the ends look the same, and the 2 hides in the middle. The page [0, 2] holds only 5s.
Input: minutes = [7, 7, 7], pages = [[0, 2], [1, 1]]
Output: [7, 7]When every minute is equal, every page returns that minute.
1 ≤ minutes.length ≤ 100,0000 ≤ minutes[i] ≤ 1,439, and minutes is a sorted list that was rotated. Equal minutes are allowed0 ≤ pages.length ≤ 100,000, and each page is [l, r] with 0 ≤ l ≤ r < minutes.lengthReading every slot of every page costs up to n × q steps, which is 10^10 when both are 100,000. A page of a rotated list has at most one break, so a comparison with its last slot can rule out half of it. But equal minutes can hide the break, and in the worst case every slot must be read, so the search is fast only when the repeats are short.