1170. Any Majority Stretches
A streaming service records one genre id per play in the array nums. A stretch of consecutive plays is called dominated if some genre appears in more than half of its entries (a strict majority, so a tie does not count). Different stretches are counted separately even when they hold the same ids.
Return how many subarrays of nums are dominated, as a long. A single element always counts. A subarray has at most one strict majority value, so nothing is counted twice. Here 1 <= n <= 10^5 and 1 <= nums[i] <= n.
For each value, track only the positions near its occurrences where its +1/-1 balance can be positive, for about O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [1,1,2]
- Output:
- 5
- Explanation:
Five subarrays qualify: [1], [1], [2], [1,1] and [1,1,2]; [1,2] has no value above half its length.
Example 2
- Input:
- nums = [1,2,3]
- Output:
- 3
- Explanation:
Only the three single elements have a majority.
Example 3
- Input:
- nums = [2,2,1,1,2]
- Output:
- 11
- Explanation:
Besides the five single elements, [2,2], [2,2,1], [2,1,1], [1,1], [1,1,2] and the whole array have a strict majority, 11 in total.
Constraints
1 ≤ n ≤ 105
1 ≤ nums[i] ≤ n
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)