Basic example
Input
arr = [1, 2, 1, 2, 3], K = 2
Output
4
The longest subarray with at most 2 distinct numbers is [1,2,1,2] with length 4.
Full lesson preview
Find the length of the longest contiguous subarray that contains at most K distinct elements using a sliding window and frequency map.
Problem statement
Task
Examples
Input
arr = [1, 2, 1, 2, 3], K = 2
Output
4
The longest subarray with at most 2 distinct numbers is [1,2,1,2] with length 4.
Input format
Output format
Constraints
Samples
Input
arr = ['a', 'b', 'a', 'b', 'c'], K = 2
Output
4
Longest window ['a','b','a','b'] length 4.