Maps app~25 min2s · 256 MBtarget O(n log R) time, O(1) spacebinary-search-answer
A maps app helps a group of friends meet on a long straight street. Each friend stands at a position, measured in metres from the start of the street, and walks at a steady speed in metres per minute. They can walk in either direction.
The group wants to meet at one point on the street as soon as possible. What is the smallest whole number of minutes after which all of them can stand at the same point?
Write meeting_time(positions, speeds).
i starts at positions[i] and walks at speeds[i] metres per minute. After t minutes, they can be at any point within speeds[i] * t metres of where they started.t such that some point on the street can be reached by every friend within t minutes. The meeting point may be any real position.Input: positions = [0, 10, 24], speeds = [1, 4, 2]
Output: 8After t minutes, friend i can reach the interval [x - v t, x + v t]. All friends can meet when the intervals share a point: the largest left end is at most the smallest right end. The answer is at most the spread, 24. Search the window [lo, hi], where hi always works.
| Step | lo | hi | mid | largest left end | smallest right end | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 24 | 12 | 0 | 12 | 0 <= 12, they can meet, so hi = 12 |
| 2 | 0 | 12 | 6 | 12 | 6 | 12 > 6, they cannot, so lo = 7 |
| 3 | 7 | 12 | 9 | 6 | 9 | 6 <= 9, so hi = 9 |
| 4 | 7 | 9 | 8 | 8 | 8 | 8 <= 8, they meet at one point, so hi = 8 |
| 5 | 7 | 8 | 7 | 10 | 7 | 10 > 7, so lo = 8 |
| end | 8 | 8 | the earliest time is 8 minutes |
At 8 minutes, the friends at 0 and 24 can both reach the point 8. The first walks 8 metres, and the third walks 16 metres at speed 2.
Input: positions = [5], speeds = [3]
Output: 0One friend is already at the meeting point, so the answer is 0, the bottom of the range.
Input: positions = [0, 10], speeds = [1, 1]
Output: 5After 5 minutes, one friend reaches [-5, 5] and the other [5, 15]. The intervals touch at the point 5, and touching is enough, so the answer is 5.
1 ≤ positions.length ≤ 100,000, and speeds.length is the same0 ≤ positions[i] ≤ 1,000,000 (metres along a straight street)1 ≤ speeds[i] ≤ 1,000 (metres per minute)Trying every whole number of minutes from 0 upwards, with a pass over the friends each time, costs about n × (the answer). The answer can be 10^6 minutes, so that is about 10^11 steps. One check costs n steps, and a binary search over the minutes, up to 10^6, needs about 20 checks, so about 2 × 10^6 steps.