Ride-hailing app~20 min2s · 256 MBtarget O(q * (rows + cols)) time, O(1) spacetraversal
You work on a ride-hailing app. Its fare table has one row for each distance band and one column for each time-of-day band. A fare never falls when you move right along a row, and never falls when you move down a column.
Rows overlap, so the first fare of a row can be smaller than the last fare of the row above. Analysts ask many price bands. For each band they want to know how many cells of the table hold a fare inside it.
Write count_in_bands(fares, lows, highs).
fares[r][c] is the fare of distance band r in time band c. Every row has the same length. Each row is in non-decreasing order, and so is each column.lows[i] and highs[i] describe band i, and lows[i] ≤ highs[i]. A fare is inside the band when lows[i] ≤ fare ≤ highs[i].Input: fares = [[2, 4, 4, 7], [3, 5, 8, 9], [3, 6, 9, 12]], lows = [4, 5, 10], highs = [8, 5, 12]
Output: [6, 1, 1]For the first band, 4 to 8, the count of fares at most 8 is 9, and the count of fares at most 3 is 3. The band holds 9 - 3 = 6 fares.
| Row | Pointer after the walk for limit 8 | Fares at most 8 | Pointer after the walk for limit 3 | Fares at most 3 |
|---|---|---|---|---|
| 0 | column 3 (fare 7) | 4 | column 0 (fare 2) | 1 |
| 1 | column 2 (fare 8) | 3 | column 0 (fare 3) | 1 |
| 2 | column 1 (fare 6) | 2 | column 0 (fare 3) | 1 |
The second band, 5 to 5, holds the single fare 5. The third band, 10 to 12, holds the single fare 12.
Input: fares = [[5]], lows = [1, 5, 6], highs = [4, 5, 9]
Output: [0, 1, 0]A band can lie below the table, on a fare, or above it.
Input: fares = [[3, 3], [3, 3]], lows = [3], highs = [3]
Output: [4]Equal fares in different cells count once each.
1 ≤ fares.length ≤ 600 (distance bands)1 ≤ fares[r].length ≤ 600 (time bands, the same for every row)1 ≤ fares[r][c] ≤ 1,000,0001 ≤ lows.length = highs.length ≤ 1,000 (bands)0 ≤ lows[i] ≤ highs[i] ≤ 1,000,000The table holds 360,000 fares. Reading all of them for each band costs 360,000,000 reads for 1,000 bands.
The order of the table lets you count with about 1,200 steps for one limit: one step for each row and each column. A band needs two limits, so 2,400 steps. For 1,000 bands that is 2,400,000 steps.