Payments app~15 min2s · 256 MBtarget O(n log k) time, O(k) spaceheaps
You work on a payments app. A risk rule looks at the amounts of the day's payments, as they arrive. Many payments have the same amount, such as a standard fee, and the rule counts each different amount once.
The rule keeps a threshold: the kth largest different amount so far. Your team lead asks: "What is the threshold after each payment?" Up to 200,000 payments arrive in a day, so sorting all the amounts again after each payment is too slow.
Write kth_distinct(k, amounts).
amounts[i] is the amount of payment i, in units. The payments arrive in the order of the list.i, look at the different values among amounts[0..i]. The threshold is the kth largest of them.k different values have arrived, there is no threshold yet, and the answer is -1.Input: k = 3, amounts = [50, 30, 50, 40, 30, 60, 20, 60, 45]
Output: [-1, -1, -1, 30, 30, 40, 40, 40, 45]| Payment | Different amounts held (the 3 largest) | Threshold |
|---|---|---|
| 50 | 50 | -1 |
| 30 | 50, 30 | -1 |
| 50 | 50, 30 (50 is already held) | -1 |
| 40 | 50, 40, 30 | 30 |
| 30 | 50, 40, 30 (30 is already held) | 30 |
| 60 | 60, 50, 40 (30 is pushed out) | 40 |
| 20 | 60, 50, 40 (20 is too small) | 40 |
| 60 | 60, 50, 40 (60 is already held) | 40 |
| 45 | 60, 50, 45 (40 is pushed out) | 45 |
Input: k = 1, amounts = [7, 3, 9, 9, 2]
Output: [7, 7, 9, 9, 9]With k = 1 the threshold is the largest amount so far.
Input: k = 2, amounts = [5, 5, 5]
Output: [-1, -1, -1]Only one different amount has arrived, so there is never a second largest.
1 ≤ amounts.length ≤ 200,000 (payments)1 ≤ amounts[i] ≤ 1,000,000,000 (units)1 ≤ k ≤ amounts.lengthSorting the different amounts after each payment costs up to 200,000 × 17 steps for each payment. For 200,000 payments that is about 680,000,000,000 steps.
A heap that holds only the k largest different amounts finds the threshold on top. Each payment costs about 17 steps for the heap and one set lookup.