Taro Logo

Subarrays with K Different Integers

#2 Most AskedHard
0 views
Topics:
ArraysSliding WindowsTwo Pointers

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.

  • For example, [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 * 104
  • 1 <= nums[i], k <= nums.length

Solution


Clarifying Questions

When 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:

  1. What are the constraints on the length of the `nums` array and the possible values of its elements, as well as the value of `k`?
  2. Can `k` be greater than the total number of elements in `nums`, or greater than the number of unique elements in `nums`?
  3. How should we handle empty inputs or when `k` is equal to zero?
  4. Does the definition of 'contiguous subarray' mean we are always looking for selections of elements from consecutive indices, and do subarrays starting at different indices count as distinct even if they contain the exact same sequence of values?
  5. Is the return value guaranteed to fit within a standard 32-bit signed integer, or should I be concerned about integer overflow for very large arrays?

Brute Force Solution

Approach

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:

  1. Look at the entire row of blocks and decide on a starting position.
  2. From that starting position, move forward step-by-step to create a smaller section of blocks by choosing different ending positions.
  3. For every section you create, count how many different colors are present inside it.
  4. Check if that count of unique colors matches your target number exactly.
  5. If the count matches, remember this section as a successful find.
  6. Repeat this process by shifting your starting position to the next block and testing all possible ending positions again until you have checked every conceivable section.
  7. Finally, count up all the successful sections you remembered along the way to get your total answer.

Code Implementation

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_sections

Big(O) Analysis

Time Complexity
O(n²) – For each of the n elements serving as a starting position in the array, an inner process moves forward step-by-step to test every possible ending position. For the first starting position, we examine up to n ending positions, for the second starting position (n-1) positions, and so on. This progression of checks totals approximately n * n/2 operations across all combinations. Simplifying this sum by dropping constant factors yields an overall time complexity of O(n²).
Space Complexity
O(K) – The auxiliary space is driven by a frequency map or hash table that tracks the unique colors and their counts within the current section of blocks. In the worst-case scenario, this map stores at most K distinct elements simultaneously corresponding to the target number of unique colors. Therefore, the memory used scales directly with K rather than the total input size N of the block array, resulting in an auxiliary space complexity of O(K).

Optimal Solution

Approach

Finding 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:

  1. Imagine scanning across a sequence of items while keeping track of the different types of items you currently see.
  2. Expand your view to the right by adding items one by one until the number of different types reaches your target limit.
  3. Every time you successfully reach the target number of different types, count all the possible valid groupings that end right at your current position.
  4. If you ever collect more types of items than your target limit, gently shrink your view from the left until you are back down to the exact target number of types.
  5. To get the precise answer, calculate how many valid groups can be formed with up to your target limit of types, and subtract the number of groups that can be formed with one fewer type.
  6. This clever trick allows you to find the exact count of groups containing the target variety of items without having to check every possible combination manually.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – The sliding window approach iterates through the n elements of the array twice, once for the helper function calculating up to k distinct elements and once for k-1 distinct elements. In each pass, the right pointer expands across all n elements while the left pointer advances at most n times total across the entire scan. Managing the frequency map takes constant time O(1) per operation since the number of unique elements is bounded. Therefore, the total operations scale linearly as approximately 2n, which simplifies to O(n).
Space Complexity
O(K) – To keep track of the different types of items currently inside the sliding window, the algorithm utilizes a hash map or frequency array. In the worst-case scenario, the number of distinct elements stored in this frequency map at any given time is bounded by the target limit K plus one. Therefore, the extra memory required scales directly with K rather than the total input size N. Consequently, the auxiliary space complexity simplifies to Big O of K.

Edge Cases

Array length is less than k
How to Handle:
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
How to Handle:
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
How to Handle:
The distinct count is one, so if k equals one it returns all possible subarrays; otherwise it returns zero.
k equals one
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Return types and intermediate counters should use 64-bit integers to prevent integer overflow.
Array contains negative numbers or zeros
How to Handle:
Hash maps treat keys as arbitrary values so negative numbers and zeros are tracked as valid distinct integers.
0/24 completed