Parcel-delivery app~15 min2s · 256 MBtarget O(n + q) time, O(n) spacehashing
A food delivery app splits each city into zones. Operations plans couriers by zone and by hour, and it asks one question again and again: how many different customers ordered in this zone during this hour?
The same customer may order several times in an hour, but they are one customer. A month of orders is available, and operations sends a long list of queries.
Write customers_per_zone_hour(zones, customers, times, qzones, qhours).
i was placed in zone zones[i] by customer customers[i] at second times[i] from the start of the month.times[i] // 3600, the whole hours since the start of the month. Hour 0 holds seconds 0 to 3599.q asks about zone qzones[q] and hour qhours[q]. Its answer is the number of different customers with an order in that zone and hour.Input: zones = [4, 4, 9, 4, 4, 9, 4], customers = [10, 11, 10, 10, 12, 10, 10], times = [100, 3500, 3700, 3800, 7300, 7300, 3900], qzones = [4, 4, 9, 4, 9], qhours = [0, 1, 1, 2, 0]
Output: [2, 1, 1, 1, 0]The trace keeps a set of customers for each (zone, hour).
| i | Zone | Customer | Second | Hour | Set for (zone, hour) after the order |
|---|---|---|---|---|---|
| 0 | 4 | 10 | 100 | 0 | (4, 0): 10 |
| 1 | 4 | 11 | 3500 | 0 | (4, 0): 10, 11 |
| 2 | 9 | 10 | 3700 | 1 | (9, 1): 10 |
| 3 | 4 | 10 | 3800 | 1 | (4, 1): 10 |
| 4 | 4 | 12 | 7300 | 2 | (4, 2): 12 |
| 5 | 9 | 10 | 7300 | 2 | (9, 2): 10 |
| 6 | 4 | 10 | 3900 | 1 | (4, 1): 10 |
The queries read (4, 0), (4, 1), (9, 1), (4, 2) and (9, 0). The sets have 2, 1, 1 and 1 customers, and (9, 0) has no set, so the output is [2, 1, 1, 1, 0]. Customer 10 ordered twice in zone 4 during hour 1, and counts once.
Input: zones = [1, 1, 1], customers = [5, 5, 5], times = [0, 1, 3599], qzones = [1], qhours = [0]
Output: [1]One customer ordered three times in the same zone and hour. The answer is 1.
Input: zones = [2], customers = [7], times = [3600], qzones = [2, 2], qhours = [0, 1]
Output: [0, 1]Second 3600 is the first second of hour 1, so the order is not in hour 0.
1 ≤ zones.length ≤ 100,000 (orders in a month); customers and times have the same length1 ≤ zones[i], customers[i] ≤ 1,000,000,000 (identifiers)0 ≤ times[i] ≤ 2,678,399 (seconds in a 31-day month)1 ≤ qzones.length ≤ 100,000 (queries); qhours has the same length1 ≤ qzones[q] ≤ 1,000,000,000, 0 ≤ qhours[q] ≤ 743Scanning all orders for every query costs n × q, about 10^10 steps. Both lists are long, so the orders must be grouped once and every query must be a single lookup. The key has two parts, a zone and an hour, and the value must hold distinct customers.