Loading content...
You are given an integer array nums and a positive integer k. Your task is to count and return the total number of qualifying subarrays within nums.
A qualifying subarray is defined as a contiguous segment of the array that contains exactly k unique (distinct) integers.
Understanding Distinct Elements: The number of distinct elements in an array is the count of unique values present. For instance, the array [4, 7, 4, 9, 7] contains exactly 3 distinct integers: 4, 7, and 9.
Understanding Subarrays: A subarray is a contiguous portion of an array, meaning elements must be adjacent to each other with no gaps. For an array of length n, there are n × (n + 1) / 2 possible non-empty subarrays.
Your goal is to enumerate all possible contiguous subarrays and count those that have precisely k different integer values.
nums = [1,2,1,2,3]
k = 27The qualifying subarrays with exactly 2 distinct integers are: [1,2] (indices 0-1), [2,1] (indices 1-2), [1,2] (indices 2-3), [2,3] (indices 3-4), [1,2,1] (indices 0-2), [2,1,2] (indices 1-3), and [1,2,1,2] (indices 0-3). Each of these contains precisely 2 unique values.
nums = [1,2,1,3,4]
k = 33The qualifying subarrays with exactly 3 distinct integers are: [1,2,1,3] (indices 0-3, contains 1,2,3), [2,1,3] (indices 1-3, contains 1,2,3), and [1,3,4] (indices 2-4, contains 1,3,4). Subarrays with fewer or more than 3 distinct values do not qualify.
nums = [1,2,3]
k = 22Only two subarrays contain exactly 2 distinct integers: [1,2] (indices 0-1) and [2,3] (indices 1-2). The full array [1,2,3] has 3 distinct values which exceeds k=2, and single-element subarrays have only 1 distinct value.
Constraints