Longest Subarray with K Distinct Values
Problem statement
Given an integer array nums and an integer k, return the longest contiguous subarray containing exactly k distinct values.
If several subarrays have the same maximum length, return the one with the smallest starting index. Return an empty array when no subarray contains exactly k distinct values.
Function
longestSubarrayWithKDistinct(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,2,1,2,3]k = 2return = [1,2,1,2]The prefix [1,2,1,2] has exactly two distinct values and is the longest valid subarray.
Example 2
nums = [1,2,1,3,4]k = 3return = [1,2,1,3]Two length-four windows are valid. The earliest one starts at index 0.
Example 3
nums = [1,1,1]k = 2return = []No subarray contains two distinct values.
Constraints
1 <= nums.length <= 100000.-10^9 <= nums[i] <= 10^9.1 <= k <= nums.length.