Ride-hailing app~20 min2s · 256 MBtarget O(n log n) time, O(n) spaceopposite-ends · sorting
You work on a ride-sharing app. Two riders can share a car when their combined luggage weight, in whole units, is inside a band. It must be at least low for the trip to pay, and at most high so the boot is not overloaded.
Your team lead asks: "How many pairs of waiting riders could share a car?" Each rider has one weight. A rider can be in many different pairs. There can be 100,000 riders.
Write count_pool_pairs(weights, low, high).
weights[i] is the luggage weight of rider i. Weights can repeat.i < j.low ≤ weights[i] + weights[j] ≤ high.Input: weights = [4, 1, 7, 3, 5], low = 6, high = 9
Output: 5Sort the weights to [1, 3, 4, 5, 7]. Count the pairs with a total of at most 9, and subtract those with a total of at most 5. The listing below is only for understanding.
| Pair of weights | Total | In the band? |
|---|---|---|
| (1, 3) | 4 | no |
| (1, 4) | 5 | no |
| (1, 5) | 6 | yes |
| (1, 7) | 8 | yes |
| (3, 4) | 7 | yes |
| (3, 5) | 8 | yes |
| (3, 7) | 10 | no |
| (4, 5) | 9 | yes |
| (4, 7) | 11 | no |
| (5, 7) | 12 | no |
There are 7 pairs with a total of at most 9, and 2 with a total of at most 5. The difference is 5.
Input: weights = [5], low = 0, high = 100
Output: 0One rider makes no pair.
Input: weights = [2, 2, 2], low = 4, high = 4
Output: 3Three equal riders make 3 pairs, each with a total of 4.
1 ≤ len(weights) ≤ 100,0001 ≤ weights[i] ≤ 1,000,0000 ≤ low ≤ high ≤ 2,000,000Checking every pair means almost 5 billion pairs, which is too slow for a 2-second limit. After sorting, the lowest and highest weights tell how many partners the lowest weight has in one step. Two pointers that move inwards then count all pairs in one pass of about 100,000 steps.