Payments app~20 min2s · 256 MBtarget O(w) expected time, O(w) spacetop-k
A payments app keeps a stream of transaction amounts in minor units. A fraud rule looks only at the latest w amounts and asks for the k-th smallest of them, for example the median.
The amounts arrive in no particular order. The rule runs often, so sorting all w amounts each time is more work than the rule needs.
Write kth_smallest_in_window(readings, w, k).
readings holds all amounts so far, oldest first. The window is the last w of them.[5, 5, 9] is 5.Input: readings = [41, 17, 29, 8, 35, 23, 12, 50], w = 6, k = 2
Output: 12The window is the last six amounts, [29, 8, 35, 23, 12, 50], and the answer is the value that would be at place 1 (counting from 0) after sorting. The table follows quick select with pivots 23 and then 12.
| Pass | Range | Pivot | Smaller | Equal | Larger | The target place is in |
|---|---|---|---|---|---|---|
| 1 | places 0 to 5 | 23 | 12, 8 | 23 | 35, 50, 29 | the smaller part |
| 2 | places 0 to 1 | 12 | 8 | 12 | none | the equal part |
The pivot of pass 2 is the answer, 12.
Input: readings = [5, 5, 5], w = 3, k = 2
Output: 5Input: readings = [9, 1, 8], w = 1, k = 1
Output: 8The window holds only the last reading.
1 ≤ readings.length ≤ 100,000 (amounts)0 ≤ readings[i] ≤ 1,000,000,000 (minor units)1 ≤ w ≤ readings.length and 1 ≤ k ≤ wRemoving the smallest value k times costs about w × k steps, which is 5 × 10^9 at w = 100,000 and k = 50,000. Sorting costs about w log w, roughly 1.7 million steps. Quick select costs about 3 to 4 times w in expectation, because each pass keeps only one side.