Social feed~25 min2s · 256 MBtarget O((n + m) log P) time, O(n + m) spacebinary-search-answer
You work on a social feed. Each post has a reach score, and each viewer group has an affinity score. The boost of a post for a group is the reach times the affinity.
The ranking team asks: "If we list the boosts of every post and group pair from the smallest, what is the k-th one?" There can be 50,000 posts and 50,000 groups, which makes 2.5 billion pairs.
Write kth_smallest_boost(reach, affinity, k).
reach[i] is the reach score of post i, and affinity[j] is the affinity score of group j. Both lists are unsorted.(i, j) has the boost reach[i] × affinity[j]. Equal boosts count as separate pairs.k-th one, counting from 1.k is at least 1 and at most len(reach) × len(affinity).Input: reach = [3, 1, 4], affinity = [2, 5, 2], k = 5
Output: 6There are nine pairs, and the sorted boosts are [2, 2, 5, 6, 6, 8, 8, 15, 20]. We do not build this list. Instead we count how many pairs have a boost at or below a limit, and search for the smallest limit that reaches 5.
| Boost limit | Pairs at or below | At least 5? |
|---|---|---|
| 5 | 3 | no |
| 6 | 5 | yes |
| 7 | 5 | yes |
A limit of 5 counts too few pairs, and 6 counts enough, so the answer is 6.
Input: reach = [7], affinity = [6], k = 1
Output: 42One pair, so the first boost is 42.
Input: reach = [2, 2], affinity = [3, 3], k = 4
Output: 6All four pairs have the boost 6, so every position gives 6.
1 ≤ len(reach), len(affinity) ≤ 50,0001 ≤ reach[i], affinity[j] ≤ 1,000,0001 ≤ k ≤ len(reach) × len(affinity), so k can reach 2,500,000,000Listing every pair means 2.5 billion boosts, which does not fit in memory and cannot be sorted in 2 seconds. But we can count the pairs at or below a limit quickly, because both lists sorted allow a two-pointer walk. The count only grows with the limit, so we can binary search the limit.