1262. Exactly-Twice Tally
A museum counts visitor badge numbers at a gate, one reading per entry, in order. For any contiguous window of readings, call a badge number twice-seen when it appears exactly two times inside that window.
Given the array nums, consider every non-empty contiguous window. For each window count its twice-seen badge numbers, then return the sum of these counts over all windows. Windows at different positions count separately. The total can exceed 32 bits, so return it as a 64-bit integer.
Enumerating windows is too slow for 200,000 readings. Aim for O(n) expected time and O(n) extra space by counting, for each pair of neighbouring occurrences of a number, how many windows have that pair as their only two occurrences.
Example 1
- Input:
- nums = [14,9,14,6,9,14,6,21,9]
- Output:
- 34
- Explanation:
Summing, over every window, the number of badge numbers seen exactly twice in it gives 34.
Example 2
- Input:
- nums = [80,35,80,12,35,12,50]
- Output:
- 19
- Explanation:
Summing, over every window, the number of badge numbers seen exactly twice in it gives 19.
Example 3
- Input:
- nums = [3,77,41,3,90,41,8,3]
- Output:
- 16
- Explanation:
Summing, over every window, the number of badge numbers seen exactly twice in it gives 16.
Constraints
1 ≤ n ≤ 2*105
1 ≤ nums[i] ≤ 109
The answer fits in a 64-bit integer.
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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)