Subarrays with K Different Integers
The problem
You are given an integer array **nums **and an integer k. Return the number of good subarrays of nums.
A good subarray is defined as a contiguous subarray of **nums **that contains exactly k distinct integers. A subarray is a contiguous part of the array.
Input: nums = [1, 2, 1, 2, 3], k = 2 Output: 7 **Explanation: **The 7 subarrays with exactly 2 different integers are: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Input: nums = [1, 2, 1, 3, 4], k = 3 Output: 3 Explanation: The 3 subarrays with exactly 3 different integers are: [1,2,1,3], [2,1,3], [1,3,4]
Input: nums = [1, 1, 1, 1], k = 1
1 <= nums.length <= 2 * 104 1 <= nums[i], k <= nums.length
cpp
class Solution {
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
// Your code goes here
}
};java
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
// Your code goes here
}
}python
class Solution:
def subarraysWithKDistinct(self, nums, k):
# Your code goes herejavascript
class Solution {
subarraysWithKDistinct(nums, k) {
// Your code goes here
}
}csharp
class Solution {
public int SubarraysWithKDistinct(int[] nums, int k) {
// Your code goes here
}
}go
func subarraysWithKDistinct(nums []int, k int) int {
// Your code goes here
}Stuck? Show a way to structure it+
- 01Define atMost(K) as the number of subarrays containing at most K distinct values.
- 02Compute atMost with a frequency map and a shrinking left boundary.
- 03Return atMost(k) minus atMost(k - 1).
- 04Make the helper return zero for a negative distinct-count limit.
Reference answer
Then expect these follow-ups
Why does a valid window contribute right - left + 1 subarrays?
Tests: counting proof
Where else can exactly(K) = atMost(K) - atMost(K-1) be used?
Tests: pattern transfer
Hiring now
ServiceNow has 794 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Senior Software Engineer, Search Infrastructure - Moveworks
Mountain View, CALIFORNIA, United States
Staff Software Engineer, AI Native Engineering, Integrations
Hyderabad, India
Software Engineer
Santa Clara, CALIFORNIA, United States
Next question