Ride-hailing app~30 min2s · 256 MBtarget O(n) on average time, O(1) spaceclassic twin: lc-215three-way-partition · two-pointers · top-k
A ride-hailing app shows riders a realistic wait before they book. For each city zone, the app reports one pickup time from the day's completed trips: the k-th fastest. The product team chooses k, for example the middle trip of the day.
The day's list of pickup times is long and in no particular order. Times are whole seconds, from 1 to 3,600, so many trips share the same time. The report needs that one time only, not the whole list in order.
Write kth_fastest(times, k).
times[i] is the pickup time of trip i, in whole seconds.k is a rank: k = 1 is the fastest pickup, and k = times.length is the slowest.k-th smallest value in times, counting repeats. If the two fastest trips both took 180 seconds, the 1st and the 2nd fastest are both 180.k is always between 1 and times.length, and the list always has at least one trip.times. The judge checks only the value you return.Input: times = [420, 180, 300, 180, 600, 240, 180, 300], k = 2
Output: 180The 2nd fastest sits at position 1 (0-based) of the sorted list. Each round partitions the range around a pivot and keeps only the block that holds position 1.
| Round | Range | Pivot (position, time) | After the partition: less, equal, greater | Position 1 falls in | Next |
|---|---|---|---|---|---|
| 1 | 0 to 7 | 7, 300 | 180, 180, 180, 240 | 300, 300 | 600, 420 | less, positions 0 to 3 | range 0 to 3 |
| 2 | 0 to 3 | 2, 180 | none | 180, 180, 180 | 240 | equal, positions 0 to 2 | return 180 |
Round 2 stops early: position 1 falls inside a block of three equal times, so there is nothing left to separate.
Input: times = [95, 60, 75], k = 3
Output: 95When k equals the number of trips, the answer is the slowest pickup.
Input: times = [300, 300, 300, 300], k = 3
Output: 300Every trip took the same time, so one partition puts them all in the equal block.
1 ≤ times.length ≤ 10^51 ≤ times[i] ≤ 36001 ≤ k ≤ times.lengthTaking the fastest trip out k times costs about n × k checks: 3.7 × 10^9 at n = 10^5 and k = n / 2. Sorting first costs about 1.7 × 10^6 comparisons and fits easily. Aim for O(n log n) at most, and O(n) on average if you can.
Read the values too. Times go up to 3,600 seconds, so 10^5 trips hold at most 3,600 distinct times. Repeats are the normal case, and the method must handle them well.