884386. Subarrays With At Most K Distinct Integers
Here is the detailed Markdown blog post for the problem "Subarrays With At Most K Distinct Integers":
Subarrays With At Most K Distinct Integers
Summary
Given an array nums and an integer k, find the number of subarrays that have at most k distinct integers. A subarray is a contiguous part of the original array.
This problem involves arrays, data structures, and algorithms. The key concept is to use a sliding window approach to efficiently count the number of subarrays with at most k distinct integers.
Detailed Explanation
We can solve this problem using a sliding window approach. Initialize two pointers, left and right, to the start of the array. Initialize a set distinct to store the distinct elements in the current window.
Step 1: Expand the window
Move the right pointer to the right until there are more than k distinct elements in the window. At each step, add the new element to the distinct set and update the size of the window.
Step 2: Shrink the window
When the number of distinct elements exceeds k, move the left pointer to the right and remove the leftmost element from the distinct set. Update the size of the window.
Step 3: Count subarrays
For each window, count the number of subarrays that have at most k distinct integers. This is done by considering all possible subarrays within the current window.
Time complexity: O(n), where n is the length of the array. Space complexity: O(k), for storing the distinct elements in the set.
Optimized Solutions
Java
public int numSubarrayKDistinct(int[] nums, int k) {
int left = 0, right = 0;
Set<Integer> distinct = new HashSet<>();
int count = 0;
while (right < nums.length) {
while (distinct.size() > k) {
distinct.remove(nums[left]);
left++;
}
if (distinct.size() <= k) {
for (int i = left; i <= right; i++) {
count += right - i + 1;
}
}
distinct.add(nums[right]);
right++;
}
return count;
}