A collector's shelf holds items in a row; kinds[i] is the category of item i. Return the number of contiguous segments of the shelf that contain exactly k different categories.
Examples
Input: kinds = [3, 3, 5, 3, 6], k = 2
Output: 6
Explanation: [3,5], [3,3,5], [5,3], [3,5,3], [3,3,5,3] and [3,6].
Input: kinds = [7, 7, 1, 9, 1, 4], k = 3
Output: 6
Explanation: [7,7,1,9], [7,1,9], [7,7,1,9,1], [7,1,9,1], [1,9,1,4] and [9,1,4].
Constraints
1 <= len(kinds) <= 10**51 <= kinds[i] <= 10**9,1 <= k <= 10**5; whenkexceeds the number of different categories on the shelf the answer is0.- Target complexity: O(n) time; enumerating all segments and counting categories is far too slow for the largest tests.
Goals
- Count subarrays with at most k distinct values in one pass
- Combine two 'at most' counts into an 'exactly' count