Count Subarrays With K Distinct Integers Problem
Description
LeetCode Problem 3859.
You are given an integer array nums and two integers k and m.
Return an integer denoting the count of subarrays of nums such that:
- The subarray contains exactly
kdistinct integers. - Within the subarray, each distinct integer appears at least
mtimes.
Example 1:
Input: nums = [1,2,1,2,2], k = 2, m = 2
Output: 2
Explanation:
The possible subarrays with k = 2 distinct integers, each appearing at least m = 2 times are:
Subarray Distinct numbers Frequency
[1, 2, 1, 2] {1, 2} → 2 {1: 2, 2: 2}
[1, 2, 1, 2, 2] {1, 2} → 2 {1: 2, 2: 3}
Thus, the answer is 2.
Example 2:
Input: nums = [3,1,2,4], k = 2, m = 1
Output: 3
Explanation:
The possible subarrays with k = 2 distinct integers, each appearing at least m = 1 times are:
Subarray Distinct numbers Frequency
[3, 1] {3, 1} → 2 {3: 1, 1: 1}
[1, 2] {1, 2} → 2 {1: 1, 2: 1}
[2, 4] {2, 4} → 2 {2: 1, 4: 1}
Thus, the answer is 3.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= k, m <= nums.length
Solution
Approach: Two Pointers
Let f(lim) count the subarrays that have at least lim distinct values and at least k values that appear m or more times. A subarray with exactly k distinct values, each at least m times, is counted by f(k) but not by f(k + 1), so the answer is f(k) - f(k + 1).
To compute f(lim) slide a window with a left pointer l. Keep the count of every value, the number of distinct values, and t, the number of values that reached m occurrences. After adding the right element, while the window has at least lim distinct values and t >= k, remove the left element and advance l. When the loop stops, the window [l, right] is no longer valid, but every start before l was valid for this right end, so add l to the total.
Complexity: O(n) time and O(n) space.
from collections import Counter
class Solution:
def countSubarrays(self, nums: List[int], k: int, m: int) -> int:
def f(lim: int) -> int:
cnt = Counter()
t = 0
ans = l = 0
for x in nums:
cnt[x] += 1
if cnt[x] == m:
t += 1
while len(cnt) >= lim and t >= k:
y = nums[l]
cnt[y] -= 1
if cnt[y] == m - 1:
t -= 1
if cnt[y] == 0:
cnt.pop(y)
l += 1
ans += l
return ans
return f(k) - f(k + 1)