K Distinct Subarray

Sliding Window Array Two Pointers Easy Medium

K Distinct Subarray

Given an array of integers and an integer k, your task is to find the length of the longest contiguous subarray that contains at most k distinct integers.

Example

  • Input: array = [1, 2, 1, 2, 3], k = 2
  • Output: 4
  • Explanation: The longest subarray with at most 2 distinct integers is [1, 2, 1, 2].

Instructions

  1. Write a function that takes in an array of integers and a positive integer k.
  2. Use a sliding window approach to efficiently solve the problem.
  3. The function should return an integer representing the length of the longest valid subarray.

Note: As we approach the end of November, a time often remembered for reflection and unity, think of this problem as finding a harmonious segment within a larger sequence, where a small number of unique values create a balanced whole.

Assume that k is at most the total number of distinct integers in the array.