Ride-hailing app~25 min2s · 256 MBtarget O(d + c) time, O(d + c) spaceclassic twin: lc-323dfs
A ride app has zones pickup zones, numbered from 0, and a list of drivers. Each driver has covered some zones during the week.
Two drivers belong to the same pool when they covered a common zone, or when a chain of drivers links them, each sharing a zone with the next. A driver who covered no zone is a pool of one.
Write count_pools(zones, coverage).
coverage[i] lists the zones driver i covered, each at most once.Input: zones = 6, coverage = [[0,1],[1,2],[3],[4,5],[5],[],[2,3]]
Output: 3A walk starts at the first driver not yet in a pool. It opens each zone of a driver once and adds every driver who covered that zone.
| Pool | Start | Zones opened | Drivers in the pool |
|---|---|---|---|
| 1 | driver 0 | 0, 1, 2, 3 | 0, 1, 6, 2 |
| 2 | driver 3 | 4, 5 | 3, 4 |
| 3 | driver 5 | none | 5 |
Driver 0 reaches driver 1 through zone 1. Driver 1 reaches driver 6 through zone 2, and driver 6 reaches driver 2 through zone 3. Drivers 3 and 4 share zone 5. Driver 5 covered nothing.
Input: zones = 3, coverage = [[0],[1],[0,1],[2]]
Output: 2Driver 2 covered zones 0 and 1, so it joins drivers 0 and 1. Driver 3 covered a zone that nobody else covered.
Input: zones = 3, coverage = [[]]
Output: 1One driver who covered nothing is one pool.
1 ≤ zones ≤ 100,0001 ≤ coverage.length ≤ 100,000, and each driver covers at most 20 zones, numbered from 0 to zones - 1Comparing every pair of drivers costs d × d / 2 = 5 × 10^9 pair checks for 100,000 drivers. Drivers meet through zones, so a list of the drivers of each zone avoids pairs. The walk then touches each driver and each zone entry once, so the work is O(d + c), where c is the number of zone entries.