Ride-hailing app~25 min2s · 256 MBtarget O(n log n) time, O(n) spacetop-k
You work on a ride-hailing app. Each finished trip is logged with the zone where it started and the place where it ended. The app wants to suggest popular drop-off places, and the best suggestions depend on the zone.
Your team lead asks: "For each zone, which k places are used most often as drop-off, most often first?" The log holds up to 200,000 trips and many different zones.
Write top_per_zone(events, k).
events[i] = [zone, place] is one trip. Zones and places are numbers.k, or all places when the zone has fewer than k.Input: events = [[2, 7], [1, 5], [2, 7], [1, 9], [2, 3], [1, 5], [2, 3], [2, 8], [1, 9], [2, 7]], k = 2
Output: [[1, 5, 9], [2, 7, 3]]| Zone | Counts of its places | The best 2 |
|---|---|---|
| 1 | place 5: 2, place 9: 2 | 5, 9 (equal counts, so the smaller place first) |
| 2 | place 7: 3, place 3: 2, place 8: 1 | 7, 3 |
Input: events = [[4, 1]], k = 3
Output: [[4, 1]]A zone with fewer than k places lists all of them.
Input: events = [[0, 2], [0, 2], [3, 2], [0, 6]], k = 1
Output: [[0, 2], [3, 2]]The zones are listed in increasing order. Each row has one place, because k = 1.
1 ≤ events.length ≤ 200,000 (trips)0 ≤ zone, place ≤ 1,000,0001 ≤ k ≤ 100Reading all the trips again for each zone costs 200,000 steps for each zone. With 100,000 zones that is 20,000,000,000 steps.
Sorting the trips once puts every zone, and every equal trip, in a row. Then one pass counts the places, and a heap of size k keeps the best ones. Sorting costs about 200,000 × 18 = 3,600,000 steps.