Maps app~15 min2s · 256 MBtarget O(n + q) time, O(n) spacecomplexity
A maps app keeps the stops of a bus route as a list of stop codes, in route order. When a rider searches for a stop, the app scans the list from the start and stops at the first match. A code that is not on the route makes the scan read the whole list.
The team wants the cost of a day of searches without running them. You will count the comparisons exactly, and the average follows by dividing by the number of searches.
Write total_comparisons(stops, queries).
stops is the route in order. Its codes are distinct.queries, a scan compares the code with stops[0], stops[1] and so on, and stops after the first equal stop.stops is compared with every stop.The average cost of a search is the total divided by the number of queries. The function returns the total, so the answer is always a whole number.
Input: stops = [40, 12, 7, 33, 19], queries = [33, 40, 99, 19, 7]
Output: 18The route has five stops. Each search stops at its match, or reads all five.
| Query | Where it sits | Comparisons |
|---|---|---|
| 33 | position 3 | 4 |
| 40 | position 0 | 1 |
| 99 | not on the route | 5 |
| 19 | position 4 | 5 |
| 7 | position 2 | 3 |
The total is 18, so the average is 3.6 comparisons a search.
Input: stops = [10, 20, 30], queries = [30, 30, 30, 5]
Output: 12Each search for 30 reads all three stops, and so does the search for the missing code 5. The total is 12.
Input: stops = [], queries = [5, 6]
Output: 0With no stops, a scan has nothing to compare, so the total is 0.
0 ≤ stops.length ≤ 100,000 (stops on a route)1 ≤ stops[i] ≤ 1,000,000, all distinct (stop codes)0 ≤ queries.length ≤ 100,000 (searches in a day)1 ≤ queries[j] ≤ 1,000,000 (searched codes)Scanning for every search costs up to 10^5 × 10^5 = 10^10 comparisons, far beyond a second. The total itself can pass 2 × 10^9, so use 64-bit integers. Look up each code's position once instead of scanning.