Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the length of the longest substring with exactly K distinct characters

Given a string and an integer K, find the length of the longest substring that contains exactly K distinct characters.

Python practice18 minStrings – Sliding Window & FrequencyIntermediateLast updated March 25, 2026

Problem statement

Given a string s and an integer k, return the length of the longest substring of s that contains exactly k distinct characters. If no such substring exists, return 0. Examples: - s = "araaci", k = 2 -> the longest substring with exactly 2 distinct characters is "araa" of length 4. - s = "cbbebi", k = 3 -> the longest is "cbbeb" or "bbebi" with length 5.

Task

Apply sliding window and frequency counting to maintain a window with exactly K distinct characters and maximize its length.

Examples

Example 1

Input

s = "araaci", k = 2

Output

4

Longest substring with exactly 2 distinct characters is "araa" (length 4).

Input format

Two inputs: a string s and an integer k.

Output format

An integer representing the length of the longest substring that contains exactly k distinct characters (0 if none).

Constraints

- 0 <= len(s) <= 10^5 - 0 <= k <= len(s) - Aim for O(n) time using a sliding window and hashmap.

Samples

Sample 1

Input

s = "cbbebi", k = 3

Output

5

Longest substrings with exactly 3 distinct characters include "cbbeb" and "bbebi" (length 5).