Ad platform~25 min2s · 256 MBtarget O((s + t) log (s + t) + (s + t) log V) time, O(s + t) spaceclassic twin: lc-475binary-search-answer
An advertising network puts display screens along one long street. Every shop on the street has a position, measured in metres from the start of the street. Every screen has a position too, and a screen can show an advert to every shop within a radius r of it, on either side.
The network wants one radius for all screens. It should be the smallest radius for which every shop has at least one screen within reach. Several shops and screens can stand at the same position.
Write smallest_radius(shops, screens).
shops[i] and screens[k] are positions along the street, in any order.p reaches the shop at position x when |x - p| <= r.r for which every shop is reached by at least one screen.Input: shops = [1, 5, 14], screens = [4, 10]
Output: 4After sorting, the trace tests a radius and keeps the lower or the upper half of the range. The range runs from 0 to 13, the distance between the leftmost and the rightmost position.
| lo | hi | r tested | Every shop reached? | Decision |
|---|---|---|---|---|
| 0 | 13 | 6 | yes | hi becomes 6 |
| 0 | 6 | 3 | no | lo becomes 4 |
| 4 | 6 | 5 | yes | hi becomes 5 |
| 4 | 5 | 4 | yes | hi becomes 4 |
The range closes at 4. The shop at 14 is 4 away from the screen at 10, and 3 is not enough for it.
Input: shops = [5], screens = [4, 10]
Output: 1The screen at 4 is the nearest to the shop at 5.
Input: shops = [0, 100], screens = [0, 100]
Output: 0Every shop has a screen at its own position.
1 ≤ shops.length ≤ 100,0001 ≤ screens.length ≤ 100,0000 ≤ shops[i], screens[k] ≤ 1,000,000,000Trying every radius from 0 up to 10^9 is far too slow. Even finding the nearest screen of every shop by a scan costs 10^5 × 10^5 = 10^10 steps. Sorting both lists and halving the radius costs about 30 sweeps of 2 × 10^5 positions each.