Social feed~20 min2s · 256 MBtarget O((n + m) log m) time, O(m) spaceclassic twin: lc-2300binary-search · sorting
A social app lets creators promote a post to groups of followers. Each creator has a boost number, and each group has a size. A promotion works when the boost times the group size reaches the campaign goal.
For every creator, the team wants to know how many groups would make the promotion work.
Write pair_counts(boosts, sizes, goal).
boosts[i] is the boost of creator i, and sizes[j] is the size of group j.(i, j) works when boosts[i] * sizes[j] >= goal.Input: boosts = [5, 1, 3, 10], sizes = [8, 2, 5, 3, 7], goal = 20
Output: [3, 0, 2, 5]Sort the sizes once: [2, 3, 5, 7, 8]. A boost b works with a size s when s >= ceil(goal / b). For the boost 3, that is ceil(20 / 3) = 7, so the search looks for the first size that is at least 7.
| Step | lo | hi | mid | sorted sizes[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 5 | 5 < 7, so lo = 3 |
| 2 | 3 | 5 | 4 | 8 | not below 7, so hi = 4 |
| 3 | 3 | 4 | 3 | 7 | not below 7, so hi = 3 |
| end | 3 | 3 | sizes from position 3 on work: 5 - 3 = 2 groups |
The boost 5 needs a size of at least 4, so three groups work. The boost 1 needs 20, so none work. The boost 10 needs 2, so all five work. The answer is [3, 0, 2, 5].
Input: boosts = [2], sizes = [], goal = 5
Output: [0]With no groups, no pair works.
Input: boosts = [1, 2, 3], sizes = [3, 3], goal = 6
Output: [0, 2, 2]The product 2 × 3 is exactly 6, and an exact product works. So the boost 2 works with both groups, as does the boost 3. The boost 1 gives 3, which is too small.
0 ≤ boosts.length ≤ 100,000 and 0 ≤ sizes.length ≤ 100,000; sizes is not sorted1 ≤ boosts[i], sizes[j] ≤ 1,000,000,0001 ≤ goal ≤ 1,000,000,000,000Trying every boost with every group costs about n × m steps, which is 10^10 when both lists have 100,000 entries. Sort the groups once. Then each boost needs one binary search. A product can reach 10^18, so do the work in 64-bit integers or divide instead of multiplying.