Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest subarray with at most K distinct elements

Find the length of the longest contiguous subarray that contains at most K distinct elements using a sliding window and frequency map.

Python practice18 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given an array (or list) arr and an integer K, return the length of the longest contiguous subarray that contains at most K distinct elements. If K is 0, return 0.

Task

Apply the variable-size sliding window technique with a frequency map to track distinct counts and maximize window length.

Examples

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.

Input format

A list arr (elements can be any hashable type) and an integer K.

Output format

An integer representing the maximum length.

Constraints

0 <= K <= len(arr) <= 10^5. Elements are hashable (e.g., ints, strings). Time O(n).

Samples

Sample 1

Input

arr = ['a', 'b', 'a', 'b', 'c'], K = 2

Output

4

Longest window ['a','b','a','b'] length 4.