Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good array is an array where the number of different integers in that array is exactly k.
[1,2,3,1,2] has 3 different integers: 1, 2, and 3.A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Example 2:
Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Constraints:
1 <= nums.length <= 2 * 1041 <= nums[i], k <= nums.lengthWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a row of colored blocks and you want to find every possible smaller section of blocks where the number of unique colors matches a specific target. The brute force approach simply examines every single possible starting point and ending point combination to see if it fits the rule.
Here's how the algorithm would work step-by-step:
def subarrays_with_k_distinct(array_of_blocks, target_colors):
total_successful_sections = 0
# Iterate through every possible starting position to examine all possible subarrays
for starting_index in range(len(array_of_blocks)):
unique_colors_found = set()
for ending_index in range(starting_index, len(array_of_blocks)):
unique_colors_found.add(array_of_blocks[ending_index])
# Stop expanding this subarray early if we exceed the allowed target count
if len(unique_colors_found) > target_colors:
break
# Accumulate this subarray if its unique color count matches our target
if len(unique_colors_found) == target_colors:
total_successful_sections += 1
return total_successful_sectionsFinding every group of items that contains a specific variety of unique elements can feel overwhelming if we check every single possibility one by one. Instead, the optimal strategy uses a clever sliding window technique to count how many valid groups can be formed efficiently.
Here's how the algorithm would work step-by-step:
class Solution:
def subarrays_with_k_distinct(self, integer_array: list[int], target_k: int) -> int:
def calculate_at_most(maximum_k):
frequency_map = {}
window_start = 0
total_count = 0
# Expand the window to the right until unique count exceeds maximum_k
for window_end in range(len(integer_array)):
current_number = integer_array[window_end]
if current_number not in frequency_map:
frequency_map[current_number] = 0
frequency_map[current_number] += 1
# Shrink window from the left if unique types exceed the allowed maximum
while len(frequency_map) > maximum_k:
left_number = integer_array[window_start]
frequency_map[left_number] -= 1
if frequency_map[left_number] == 0:
del frequency_map[left_number]
window_start += 1
total_count += window_end - window_start + 1
return total_count
# Subtract subsets with fewer unique elements to isolate exact k distinct integers
return calculate_at_most(target_k) - calculate_at_most(target_k - 1)| Case | How to Handle |
|---|---|
| Array length is less than k | The sliding window approach will naturally find zero valid subarrays and return zero. |
| k is greater than the total number of elements in the array | Since there are fewer distinct elements than k, the distinct count will never reach k and return zero. |
| All elements in the array are identical | The distinct count is one, so if k equals one it returns all possible subarrays; otherwise it returns zero. |
| k equals one | The atMostK function computes subarrays with at most one distinct integer, which correctly solves the base case. |
| Array contains large integer values or extreme boundary values | Using hash maps instead of frequency arrays prevents out-of-bounds errors and handles sparse integer ranges efficiently. |
| Maximum-sized inputs up to tens of thousands of elements | The two-pointer sliding window runs in linear time O(n) which easily scales within time limits. |
| Total number of good subarrays exceeds 32-bit integer limit | Return types and intermediate counters should use 64-bit integers to prevent integer overflow. |
| Array contains negative numbers or zeros | Hash maps treat keys as arbitrary values so negative numbers and zeros are tracked as valid distinct integers. |