Ride-hailing app~15 min2s · 256 MBtarget O(r log c + r log r) time, O(r) spaceclassic twin: lc-1337binary-search
A ride-hailing app keeps a roster for every city zone. A roster lists the zone's driver slots in the order drivers sign off. A slot holds 1 while the driver is on shift and 0 after the driver signs off.
Drivers never come back on shift once they sign off, so every roster reads as some 1s and then only 0s. All rosters have the same number of slots. The operations team wants to know which zones are short of drivers.
Write weakest_zones(rosters, k).
rosters[z] is the roster of zone z, counting zones from 0.k weakest zones, from the weakest to the strongest of them.Input: rosters = [[1,1,1,0,0], [1,0,0,0,0], [1,1,1,1,1], [1,1,0,0,0]], k = 2
Output: [1, 3]The zones have 3, 1, 5 and 2 drivers on shift. The two weakest are zone 1 and zone 3. The trace finds the count of zone 0 by searching for the first 0 in its roster. The window runs from lo to hi, and the first 0 is at lo when the window closes.
| Step | lo | hi | mid | Slot at mid | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 1 | still on shift: lo becomes 3 |
| 2 | 3 | 5 | 4 | 0 | signed off: hi becomes 4 |
| 3 | 3 | 4 | 3 | 0 | signed off: hi becomes 3 |
The window closes at 3, so zone 0 has 3 drivers on shift.
Input: rosters = [[1,0], [1,0], [0,0]], k = 2
Output: [2, 0]Zone 2 has no drivers. Zones 0 and 1 tie with one driver, and the smaller number comes first.
Input: rosters = [[1,1,1]], k = 1
Output: [0]A single zone is also the weakest one.
1 ≤ rosters.length ≤ 3,000 (zones)1 ≤ rosters[z].length ≤ 1,000 (slots in a roster, the same for every zone)1 ≤ k ≤ rosters.lengthCounting every slot of every zone costs rows × columns, which is at most 3,000,000 reads, so that part is fast. Picking the weakest zone again for each of the k answers costs about rows × k, which is up to 9,000,000 row counts. Each count is up to 1,000 reads. That is about 9 × 10^9 reads, over the budget, so the selection also needs a sort.