Music streaming app~35 min4s · 256 MBtarget O(n log n + q) time, O(n log n) spacesegment-tree
You work on a streaming app. A radio channel plays a loop of up to 100,000 slots, and each slot has a popularity score. When the last slot ends, the loop starts again at slot 0.
Programmers look at windows of consecutive slots. A window can start near the end and carry on from slot 0. Your team lead asks: "For each window, how far apart are the most popular and the least popular slot?" The scores never change, and there are up to 100,000 windows.
Write swing_of_windows(scores, windows).
scores[i] is the popularity of slot i.windows[k] = [start, length] is the window of length slots that begins at slot start. After the last slot it continues at slot 0.Input: scores = [5, 1, 4, 2, 8, 3], windows = [[1, 3], [4, 4], [0, 6]]
Output: [3, 7, 7]| Window | Slots | Scores | Highest - lowest |
|---|---|---|---|
[1, 3] |
1, 2, 3 | 1, 4, 2 | 4 - 1 = 3 |
[4, 4] |
4, 5, 0, 1 | 8, 3, 5, 1 | 8 - 1 = 7 |
[0, 6] |
0 to 5 | 5, 1, 4, 2, 8, 3 | 8 - 1 = 7 |
Input: scores = [9], windows = [[0, 1]]
Output: [0]One slot is both the highest and the lowest.
Input: scores = [4, 4, 4], windows = [[0, 3], [2, 2]]
Output: [0, 0]Equal scores have no swing.
1 ≤ len(scores) ≤ 100,0000 ≤ scores[i] ≤ 1,000,0001 ≤ len(windows) ≤ 100,0000 ≤ start < len(scores) and 1 ≤ length ≤ len(scores).Walking over a window costs up to 100,000 steps, and 100,000 windows cost 10 billion steps. That is too slow. The list never changes, so you can prepare tables once and answer each window in a constant number of steps. Preparing the tables costs about n log n, which is 1.7 million steps.