Social feed~20 min2s · 256 MBtarget O(n log n) time, O(n) spacedifference-array
A social app promotes posts in its feed. Each promotion runs from a start minute up to, but not including, an end minute. Minutes are counted from a fixed starting point and reach 1,000,000,000.
Two promotions that run at the same time compete for attention. The ads team wants to know for how many minutes at least two promotions run together. Up to 100,000 promotions arrive in one plan.
Write minutes_with_overlap(promotions).
promotions[i] is [start, end] with 0 <= start < end <= 1,000,000,000. Promotion i runs in the minutes start, start + 1, ..., end - 1. The minute end is not part of it.Input: promotions = [[2, 7], [5, 10], [6, 8], [12, 15]]
Output: 3Make two events for each promotion, sort them, and add the gap before an event when two or more promotions were running.
| Event minute | Change | Running before | Minutes added | Running after |
|---|---|---|---|---|
| 2 | +1 | 0 | 0 | 1 |
| 5 | +1 | 1 | 0 | 2 |
| 6 | +1 | 2 | 1 | 3 |
| 7 | -1 | 3 | 1 | 2 |
| 8 | -1 | 2 | 1 | 1 |
| 10 | -1 | 1 | 0 | 0 |
| 12 | +1 | 0 | 0 | 1 |
| 15 | -1 | 1 | 0 | 0 |
The minutes 5, 6 and 7 each have two or more promotions running: 3 minutes.
Input: promotions = [[0, 5], [5, 9]]
Output: 0The promotions touch at minute 5 and do not overlap.
Input: promotions = [[1, 4]]
Output: 0One promotion cannot overlap with itself.
1 ≤ promotions.length ≤ 100,0000 ≤ start < end ≤ 1,000,000,000 (minutes)An array with one place for every minute would hold 10^9 entries, about 4 GB with 32-bit entries. That is too much memory and too slow to scan.
Only the 2 × 10^5 start and end minutes matter. Sort them in O(n log n) and sweep.