Maps app~12 min2s · 256 MBtarget O(n) time, O(1) spacenumber-theory
A long road has a numbered marker at every fixed distance: marker 4, then marker 9, then marker 14, and so on. A survey app stores the numbers of all markers in order.
One marker was stolen from the middle of the road. The first and the last markers are still there. You want the app to tell the road crew which number to put back.
Write missing_marker(markers).
markers lists the surviving marker numbers, from the lowest to the highest.markers[0] to the last marker.Input: markers = [4, 9, 14, 24, 29]
Output: 19The table compares the sum the full road would have with the sum of what survives.
| Quantity | Value |
|---|---|
| Markers that survive (n) | 5 |
| Markers on the full road (n + 1) | 6 |
| First and last | 4 and 29 |
| Expected sum (4 + 29) × 6 / 2 | 99 |
| Sum of the surviving markers | 80 |
| Expected sum minus surviving sum | 19 |
The step is 5, so the full road is 4, 9, 14, 19, 24, 29. Marker 19 is gone.
Input: markers = [2, 3, 5]
Output: 4The step is 1, and the full road is 2, 3, 4, 5. Marker 4 is gone.
Input: markers = [10, 30]
Output: 20Only the first and the last markers survive. Three markers fit between 10 and 30 only if the step is 10, so marker 20 is missing.
2 ≤ markers.length ≤ 100,000 (surviving markers)0 ≤ markers[i] ≤ 1,000,000; the numbers rise with an equal step, except for the one gapLooking for each expected number in the list costs about n × n / 2 checks, 5 × 10^9 at n = 100,000. The full road has a known sum, because its markers form an equally spaced run. One pass that adds up the surviving numbers is enough.