Last Updated: 30 Sep, 2025

K-Distinct Character Substring

Moderate
Asked in company
Delhivery

Problem statement

You are given a string s consisting of lowercase English alphabets and an integer k. Your task is to find the length of the longest substring of s that contains exactly k distinct characters.


If no such substring exists, you should return -1.


Input Format:
The first line of input contains the string s.

The second line of input contains the integer k.


Output Format:
Print a single integer representing the length of the longest substring with exactly k distinct characters.

If no such substring is found, print -1.


Note:
A naive solution of checking every possible substring (O(N^2)) would be too slow for the given constraints.