Maps app~40 min4s · 256 MBtarget O((n + q) sqrt(n)) time, O(n) spacedivide-and-conquer
You work on a maps app for electric cars. A highway has length kilometre marks, numbered from 0, and some marks already have a charging station. New stations open over time.
Drivers ask how far the nearest station is from their kilometre mark. Your team lead asks: "Can we answer every question straight away, even while new stations keep opening?" There are up to 30,000 kilometre marks and 30,000 operations.
Write nearest_station(stations, length, ops).
stations lists the kilometre marks that have a station at the start. At least one station exists. Marks can repeat.length is the number of kilometre marks, so every mark is from 0 to length - 1.[kind, x].[0, x] opens a new station at mark x.[1, x] is a question: what is the distance, in kilometres, from mark x to the nearest station? The distance is 0 when x has a station.Input: stations = [2], length = 10, ops = [[1, 7], [0, 6], [1, 7], [0, 0], [1, 1], [0, 9], [1, 8]]
Output: [5, 1, 1, 1]| Operation | Stations after it | Answer |
|---|---|---|
[1, 7] |
2 | 7 - 2 = 5 |
[0, 6] |
2, 6 | |
[1, 7] |
2, 6 | 7 - 6 = 1 |
[0, 0] |
2, 6, 0 | |
[1, 1] |
2, 6, 0 | 1 - 0 = 1 (also 2 - 1 = 1) |
[0, 9] |
2, 6, 0, 9 | |
[1, 8] |
2, 6, 0, 9 | 9 - 8 = 1 |
Input: stations = [0], length = 1, ops = [[1, 0], [0, 0], [1, 0]]
Output: [0, 0]A highway of one kilometre mark has its only station on it.
Input: stations = [3], length = 6, ops = [[1, 3], [1, 0]]
Output: [0, 3]Asking at the station itself gives 0. Mark 0 is 3 kilometres from mark 3.
1 ≤ length ≤ 30,0001 ≤ len(stations) ≤ 30,000, and every mark is from 0 to length - 11 ≤ len(ops) ≤ 30,000kind is 0 or 1, and 0 ≤ x < length.Measuring the distance to every station for each question costs up to 30,000 steps, and 30,000 questions cost 900 million steps. That is too slow. A table of distances answers a question in one step, but rebuilding it costs a pass over the highway, so you cannot rebuild it after every new station.