Sliding window · Medium
A telemetry analysis counts continuous periods containing exactly a requested number of event types. Repeated occurrences do not increase the number of types, but different start and end positions still describe different periods.
Return the count of non-empty contiguous segments containing exactly k distinct values.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], k: integer }
Fields
- nums is an array of signed integers. Repeated values at different positions are separate entries.
- k is the exact number of distinct values required inside a segment.
Output
Return value
- Return one integer count of index ranges. Do not deduplicate ranges with identical contents.
- Return 0 when k is zero, k exceeds the number of available distinct values, or input is empty.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
- 0 <= k <= 100000.
Examples
Example 1
{
"k": 2,
"nums": [
1,
2,
1,
2,
3
]
}Returns
7Example 2
{
"k": 1,
"nums": [
1,
1
]
}Returns
3Required complexity
O(n) expected time and O(min(n, k + 1)) auxiliary space