Update appNew update is available. Click here to update.

Longest Sub-string with at most K Distinct Characters

Contributed by
Dhruv Sharma
Last Updated: 23 Feb, 2023
Medium
yellow-spark
0/80
Avg time to solve 35 mins
Success Rate 65 %
Share
21 upvotes

Problem Statement

You are given string S of length N, and an integer K. Your task is to find the length of the longest substring that contains at most K distinct characters.

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 10
1 <= K <= 26
1 <= N <= 10^4

Time Limit: 1sec
Sample Input 1:
2
2
abcba
1
abccc
Sample Output 1:
3
3
Explanation of the Sample Input1:
Test Case 1:
K = 2 in the first test case so we can choose substring ‘bcb’ having 2 distinct characters which are less than equal to K=2. 
We cannot get any other substring of length 4 or greater having distinct characters less than equal to 2.
Test Case 2:
K = 1 in the second test case so we can choose substring ‘ccc’ having only 1 distinct character which is less than equal to K=1. 
We cannot get any other substring of length 4 or greater having distinct characters less than equal to 1.
Reset Code
Full screen
Auto
copy-code
Console