Music streaming app~30 min2s · 256 MBtarget O(log n + q log n) time, O(1) spaceclassic twin: lc-1095binary-search
A music streaming app tracks how many people listen live to a concert, minute by minute. The audience grows until the peak, and after that it only shrinks. It never stays level from one minute to the next.
An analyst asks about many audience sizes. For each size, at which minute did the live audience first reach exactly that number? Minutes count from 0.
Write find_in_mountain(profile, queries).
profile[i] is the audience at minute i. The values strictly rise to one peak and then strictly fall.i with profile[i] == query.Input: profile = [2, 5, 9, 12, 10, 7, 5, 1], queries = [5, 12, 7, 13, 0]
Output: [1, 3, 5, -1, -1]First find the peak. If the next minute has a larger audience, the peak is to the right. Then search the rising side for the query. If it is not there, search the falling side.
| Step | lo | hi | mid | profile[mid] | profile[mid + 1] | Decision |
|---|---|---|---|---|---|---|
| peak 1 | 0 | 7 | 3 | 12 | 10 | 12 < 10 is false, so hi = 3 |
| peak 2 | 0 | 3 | 1 | 5 | 9 | 5 < 9, so lo = 2 |
| peak 3 | 2 | 3 | 2 | 9 | 12 | 9 < 12, so lo = 3 |
The peak is at minute 3. The query 5 is found on the rising side at minute 1, and not at minute 6 on the falling side. The query 12 is the peak, minute 3.
The query 7 is only on the falling side, minute 5. The queries 13 and 0 are never reached. The answer is [1, 3, 5, -1, -1].
Input: profile = [1, 3, 2], queries = [1, 2, 3, 4]
Output: [0, 2, 1, -1]The shortest mountain has three minutes. The peak, 3, is at minute 1. The query 2 is on the falling side, at minute 2.
Input: profile = [1, 4, 9, 4, 1], queries = [4, 1]
Output: [1, 0]The values 4 and 1 appear on both sides. The smallest minute wins, so the answers are 1 and 0, from the rising side.
3 ≤ profile.length ≤ 100,0000 ≤ queries.length ≤ 100,0000 ≤ profile[i], queries[j] ≤ 1,000,000 (viewers)Scanning the whole profile for every number costs about n × q steps, which is 10^10 when both are 100,000. The profile is sorted on each side of the peak, so find the peak once with a binary search and then search each side with another one. That is about 17 steps once, then at most 2 × 17 steps per question.