Showing:
Handle Score
@Ibrahim Nash 6420
@mb1973 5578
@Quandray 5231
@akhayrutdinov 5111
@saiujwal13083 4510
@sanjay05 3762
@kirtidee18 3673
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3412
Longest K unique characters substring
Easy Accuracy: 53.69% Submissions: 1929 Points: 2

Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.

Example 1:

Input:
S = "aabacbebebe", K = 3
Output: 7
Explanation: "cbebebe" is the longest
substring with K distinct characters.


â€‹Example 2:

Input:
S = "aaaa", K = 2
Output: -1
Explanation: There's no substring with K
distinct characters.


You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1.

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).

Constraints:
1<=|S|<=105
1<=K<=105

### Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

#### My Submissions:

Longest K unique characters substring