Longest substring with k unique characters
Last Updated :
06 Mar, 2025
Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them.
Note:- Source(Google Interview Question).
Examples:
Input: Str = "aabbcc", k = 1
Output: 2
Explanation: Max substring can be any one from ["aa" , "bb" , "cc"].
Input: Str = "aabbcc", k = 2
Output: 4
Explanation: Max substring can be any one from ["aabb" , "bbcc"].
Input: Str = "aabbcc", k = 3
Output: 6
Explanation: There are substrings with exactly 3 unique characters
["aabbcc" , "abbcc" , "aabbc" , "abbc" ]
Max is "aabbcc" with length 6.
Input: Str = "aaabbb", k = 3
Output: -1
Explanation: There are only two unique characters, thus show error message.
[Naive Approach] - Generate all Substring - O(n^2) Time and O(n) Space
For a string of length n, there are n * (n + 1) / 2 possible substrings. A straightforward approach is to generate all substrings and check if each contains exactly k unique characters. Using brute force, this takes O(n²) to generate substrings and O(n) for each check, leading to an overall time complexity of O(n³).
C++
#include <bits/stdc++.h>
using namespace std;
int longestKSubstr(string s, int k)
{
int n = s.length();
int answer = -1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
unordered_set<char> distinct(s.begin() + i,
s.begin() + j);
if (distinct.size() == k) {
answer = max(answer, j - i);
}
}
}
return answer;
}
int main()
{
string s = "aabacbebebe";
int k = 3;
cout<<longestKSubstr(s, k);
return 0;
}
Java
import java.util.*;
class GfG {
static int longestKSubstr(String s, int k)
{
int n = s.length();
int answer = -1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
HashSet<Character> distinct
= new HashSet<Character>();
for (int x = i; x < j; x++) {
distinct.add(s.charAt(x));
}
if (distinct.size() == k) {
answer = Math.max(answer, j - i);
}
}
}
return answer;
}
public static void main(String[] args)
{
String s = "aabacbebebe";
int k = 3;
System.out.print(longestKSubstr(s, k));
}
}
// This code is contributed by garg28harsh.
Python
def longestKSubstr(s, k):
n = len(s)
answer = -1
for i in range(n):
for j in range(i+1, n+1):
distinct = set(s[i:j])
if len(distinct) == k:
answer = max(answer, j - i)
return answer
s = "aabacbebebe"
k = 3
# Function Call
print(longestKSubstr(s, k))
C#
// C# program to find ceil of a given value in BST
using System;
using System.Collections.Generic;
class GfG {
static int longestKSubstr(string s, int k)
{
int n = s.Length;
int answer = -1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
HashSet<char> distinct
= new HashSet<char>();
for (int x = i; x < j; x++) {
distinct.Add(s[x]);
}
if (distinct.Count == k) {
answer = Math.Max(answer, j - i);
}
}
}
return answer;
}
public static void Main(string[] args)
{
String s = "aabacbebebe";
int k = 3;
// Function Call
Console.WriteLine(longestKSubstr(s, k));
}
}
JavaScript
function longestKSubstr(s, k) {
let n = s.length;
let answer = -1;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j <= n; j++) {
let distinct = new Set();
for (let x = i; x < j; x++) {
distinct.add(s.charAt(x));
}
if (distinct.size === k) {
answer = Math.max(answer, j - i);
}
}
}
return answer;
}
let s = "aabacbebebe";
let k = 3;
console.log(longestKSubstr(s, k));
[Expected Approach] - Sliding window with Array - O(n) Time and O(1) Space
The problem can be solved in O(n) using a sliding window approach. We expand the window by adding elements until it contains at most k unique characters, updating the result as needed. If the number of unique characters exceeds k, we shrink the window from the left until it meets the condition again. To count the number of unique elements we will use array.
C++
#include <bits/stdc++.h>
using namespace std;
bool isValid(vector<int> &count, int k)
{
int val = 0;
for (int i = 0; i < 26; i++)
if (count[i] > 0)
val++;
return (k >= val);
}
int longestKSubstr(string &s, int k)
{
int u = 0;
int n = s.length();
vector<int> count(26, 0);
// Count unique characters
for (int i = 0; i < n; i++)
{
if (count[s[i] - 'a'] == 0)
u++;
count[s[i] - 'a']++;
}
if (u < k)
{
return -1;
}
int curr_start = 0, max_window_size = 0;
// Reset count array
fill(count.begin(), count.end(), 0);
for (int curr_end = 0; curr_end < n; curr_end++)
{
count[s[curr_end] - 'a']++; // Expand window
// Shrink window if unique characters exceed k
while (!isValid(count, k))
{
count[s[curr_start] - 'a']--;
curr_start++;
}
// Update max window size
max_window_size = max(max_window_size, curr_end - curr_start + 1);
}
return max_window_size;
}
// Driver function
int main()
{
string s = "aabacbebebe";
int k = 3;
cout << longestKSubstr(s, k) << "\n";
return 0;
}
Java
import java.util.Arrays;
class GfG {
static boolean isValid(int count[],
int k)
{
int val = 0;
for (int i = 0; i < 26; i++)
{
if (count[i] > 0)
{
val++;
}
}
return (k >= val);
}
static int longestKSubstr(String s, int k)
{
int u = 0;
int n = s.length();
// Associative array to store
// the count of characters
int count[] = new int[26];
Arrays.fill(count, 0);
for (int i = 0; i < n; i++)
{
if (count[s.charAt(i) - 'a'] == 0)
{
u++;
}
count[s.charAt(i) - 'a']++;
}
if (u < k) {
return -1;
}
int curr_start = 0, curr_end = 0;
int max_window_size = 1;
// Initialize associative
// array count[] with zero
Arrays.fill(count, 0);
// put the first character
count[s.charAt(0) - 'a']++;
for (int i = 1; i < n; i++) {
// Add the character 's[i]'
// to current window
count[s.charAt(i) - 'a']++;
curr_end++;
while (!isValid(count, k)) {
count[s.charAt(curr_start) - 'a']--;
curr_start++;
}
// Update the max window size if required
if (curr_end - curr_start + 1 > max_window_size)
{
max_window_size = curr_end - curr_start + 1;
}
}
return max_window_size;
}
// Driver Code
static public void main(String[] args) {
String s = "aabacbebebe";
int k = 3;
System.out.print(longestKSubstr(s, k));
}
}
Python
def isValid(count, k):
val = 0
for i in range(26):
if count[i] > 0:
val += 1
# Return true if k is greater than or equal to val
return (k >= val)
# Finds the maximum substring with exactly k unique characters
def longestKSubstr(s, k):
u = 0
n = len(s)
# Associative array to store the count
count = [0] * 26
for i in range(n):
if count[ord(s[i])-ord('a')] == 0:
u += 1
count[ord(s[i])-ord('a')] += 1
if u < k:
return -1
# Otherwise take a window with first element in it.
# start and end variables.
curr_start = 0
curr_end = 0
# Also initialize values for result longest window
max_window_size = 1
# Initialize associative array count[] with zero
count = [0] * len(count)
count[ord(s[0])-ord('a')] += 1 # put the first character
for i in range(1,n):
# Add the character 's[i]' to current window
count[ord(s[i])-ord('a')] += 1
curr_end+=1
# If there are more than k unique characters in
# current window, remove from left side
while not isValid(count, k):
count[ord(s[curr_start])-ord('a')] -= 1
curr_start += 1
# Update the max window size if required
if curr_end-curr_start+1 > max_window_size:
max_window_size = curr_end-curr_start+1
return max_window_size
# Driver function
s = "aabacbebebe"
k = 3
print(longestKSubstr(s, k))
C#
using System;
public class GfG {
static bool isValid(int[] count, int k)
{
int val = 0;
for (int i = 0; i < 26; i++) {
if (count[i] > 0) {
val++;
}
}
return (k >= val);
}
static int longestKSubstr(string s, int k)
{
int u = 0;
int n = s.Length;
// Associative array to store the count of
// characters
int[] count = new int[26];
Array.Fill(count, 0);
for (int i = 0; i < n; i++) {
if (count[s[i] - 'a'] == 0) {
u++;
}
count[s[i] - 'a']++;
}
if (u < k) {
return -1;
}
int curr_start = 0, curr_end = 0;
int max_window_size = 1;
// Reset count array
Array.Fill(count, 0);
// Put the first character in the count array
count[s[0] - 'a']++;
for (int i = 1; i < n; i++) {
count[s[i] - 'a']++;
curr_end++;
// If unique characters exceed k, shrink window
while (!isValid(count, k)) {
count[s[curr_start] - 'a']--;
curr_start++;
}
// Update max window size
if (curr_end - curr_start + 1
> max_window_size) {
max_window_size = curr_end - curr_start + 1;
}
}
return max_window_size;
}
static public void Main()
{
string s = "aabacbebebe";
int k = 3;
Console.WriteLine(longestKSubstr(s, k));
}
}
JavaScript
function isValid(count, k)
{
let val = 0;
for(let i = 0; i < 26; i++)
{
if (count[i] > 0)
{
val++;
}
}
return (k >= val);
}
function longestKSubstr(s,k)
{
// Number of unique characters
let u = 0;
let n = s.length;
let count = new Array(26);
for(let i = 0; i < 26; i++)
{
count[i] = 0;
}
for(let i = 0; i < n; i++)
{
if (count[s[i].charCodeAt(0) -
'a'.charCodeAt(0)] == 0)
{
u++;
}
count[s[i].charCodeAt(0) -
'a'.charCodeAt(0)]++;
}
if (u < k)
{
return -1;
}
let curr_start = 0, curr_end = 0;
let max_window_size = 1;
// Initialize associative
// array count[] with zero
for(let i = 0; i < 26; i++)
{
count[i] = 0;
}
// put the first character
count[s[0].charCodeAt(0) -
'a'.charCodeAt(0)]++;
for(let i = 1; i < n; i++)
{
// Add the character 's[i]'
// to current window
count[s[i].charCodeAt(0) -
'a'.charCodeAt(0)]++;
curr_end++;
while (!isValid(count, k))
{
count[s[curr_start].charCodeAt(0) -
'a'.charCodeAt(0)]--;
curr_start++;
}
// Update the max window size if required
if (curr_end - curr_start + 1 > max_window_size)
{
max_window_size = curr_end - curr_start + 1;
}
}
return max_window_size;
}
// Driver Code
let s = "aabacbebebe";
let k = 3;
console.log(longestKSubstr(s, k));
[Alternate Approach] Sliding window with Hash Map or Dictionary - O(n) Time and O(1) Space
We use a Hash Map to track character frequencies and apply the acquire and release strategy with two pointers, i and j. The i pointer expands the window, adding characters until the map size exceeds K. When it equals K, we record the substring length. If the size surpasses K, we shrink the window using j, updating the length accordingly. This process continues to find the optimal result.
C++
#include <bits/stdc++.h>
using namespace std;
int longestKSubstr(string s, int k)
{
int i = 0;
int j = 0;
int ans = -1;
unordered_map<char, int> mp;
while (j < s.size()) {
mp[s[j]]++;
while (mp.size() > k) {
mp[s[i]]--;
if (mp[s[i]] == 0)
mp.erase(s[i]);
i++;)
}
if (mp.size() == k) {
ans = max(ans, j - i + 1);
}
j++;
}
return ans;
}
int main()
{
string s = "aabacbebebe";
int k = 3;
cout << longestKSubstr(s, k) << endl;
return 0;
}
Java
import java.io.*;
import java.util.*;
class GfG {
static int longestkSubstr(String S, int k)
{
// code here
Map<Character, Integer> map = new HashMap<>();
int i = -1;
int j = -1;
int ans = -1;
while (true) {
boolean flag1 = false;
boolean flag2 = false;
while (i < S.length() - 1) {
flag1 = true;
i++;
char ch = S.charAt(i);
map.put(ch, map.getOrDefault(ch, 0) + 1);
if (map.size() < k)
continue;
else if (map.size() == k) {
int len = i - j;
ans = Math.max(len, ans);
}
else
break;
}
while (j < i) {
flag2 = true;
j++;
char ch = S.charAt(j);
if (map.get(ch) == 1)
map.remove(ch);
else
map.put(ch, map.get(ch) - 1);
if (map.size() == k) {
int len = i - j;
ans = Math.max(ans, len);
break;
}
else if (map.size() > k)
continue;
}
if (flag1 == false && flag2 == false)
break;
}
return ans;
}
public static void main(String[] args)
{
String s = "aabacbebebe";
int k = 3;
int ans = longestkSubstr(s, k);
System.out.println(ans);
}
}
Python
def longestkSubstr(S, k):
map = {}
i = -1
j = -1
# Initialize ans to -1
ans = -1
while True:
flag1 = False
flag2 = False
while i < len(S) - 1:
flag1 = True
i += 1
ch = S[i]
map[ch] = map.get(ch, 0) + 1
if len(map) < k:
continue
elif len(map) == k:
len_ = i - j
ans = max(len_, ans)
else:
break
while j < i:
# Set flag2 to True
flag2 = True
j += 1
ch = S[j]
# If character count is 1, remove character from dictionary
if map[ch] == 1:
del map[ch]
else:
map[ch] -= 1
if len(map) == k:
len_ = i - j
ans = max(ans, len_)
break
# If number of unique characters is greater than k, continue loop
elif len(map) > k:
continue
# If both flags are False, break outer loop (while True)
if not flag1 and not flag2:
break
return ans
s = "aabacbebebe"
k = 3
ans = longestkSubstr(s, k)
print(ans)
C#
using System;
using System.Collections.Generic;
class GfG {
static int longestKSubstr(string s, int k)
{
int i = 0;
int j = 0;
int ans = -1;
Dictionary<char, int> mp
= new Dictionary<char, int>();
while (j < s.Length) {
if (mp.ContainsKey(s[j])) {
mp[s[j]]++;
}
else {
mp[s[j]] = 1;
}
while (mp.Count > k) {
mp[s[i]]--;
if (mp[s[i]] == 0) {
mp.Remove(s[i]);
}
i++;
}
if (mp.Count == k) {
ans = Math.Max(ans, j - i + 1);
}
j++;
}
return ans;
}
public static void Main()
{
string s = "aabacbebebe";
int k = 3;
Console.WriteLine(longestKSubstr(s, k));
}
}
JavaScript
function longestKSubstr(s, k) {
let i = 0;
let j = 0;
let ans = -1;
let mp = new Map();
while (j < s.length) {
mp.set(s[j], (mp.get(s[j]) || 0) + 1);
while (mp.size > k) {
mp.set(s[i], mp.get(s[i]) - 1);
if (mp.get(s[i]) === 0) {
mp.delete(s[i]);
}
i++;
}
if (mp.size === k) {
ans = Math.max(ans, j - i + 1);
}
j++;
}
return ans;
}
let s = "aabacbebebe";
let k = 3;
console.log(longestKSubstr(s, k));
Similar Reads
Largest substring with same Characters Given a string s of size N. The task is to find the largest substring which consists of the same charactersExamples: Input : s = "abcdddddeff" Output : 5 Substring is "ddddd"Input : s = aabceebeee Output : 3 Approach : Traverse through the string from left to right. Take two variables ans and temp.
4 min read
Longest Substring Without Repeating Characters Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples:Input: s = "geeksforgeeks"Output: 7 Explanation: The longest substrings without repeating characters are "eksforgâ and "ksforge", with lengths of 7.Input: s = "aaa"Output: 1E
12 min read
String with maximum number of unique characters Given an array of strings, the task is to print the string with the maximum number of unique characters.Note: Strings consists of lowercase characters.If multiple strings exists, then print any one of them.Examples: Input: arr[] = ["abc", "geeksforgeeks", "gfg", "code"]Output: "geeksforgeeks" Explan
5 min read
Count substrings with k distinct characters Given a string s consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are ["ab", "bc"]Input: s = "aba", k = 2Out
10 min read
Length of the longest substring with consecutive characters Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string "dfabck" will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... Examples: Input: str =
7 min read
Print Longest substring without repeating characters Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples:Input: s = âgeeksforgeeksâOutput: 7 Explanation: The longest substrings without repeating characters are âeksforgâ and âksforgeâ, with lengths of 7.Input: s = âaaaâOutput: 1E
14 min read
Longest Common Subsequence with no repeating character Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character. Examples: Input: s1= "aabbcc", s2= "aabc"Output: 3Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.So the required longest common subsequ
10 min read
Longest subsequence with different adjacent characters Given string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different. Examples:Â Â Input: str = "ababa"Â Output: 5Â Explanation:Â "ababa" is the subsequence satisfying the condition Input: str = "xxxxy"Â Output: 2Â Explan
14 min read
Find length of longest substring with at most K normal characters Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P =
11 min read
Longest substring where all the characters appear at least K times | Set 3 Given a string str and an integer K, the task is to find the length of the longest substring S such that every character in S appears at least K times. Examples: Input: str = âaabbbaâ, K = 3Output: 6Explanation: In substring "aabbba", each character repeats at least k times and its length is 6. Inpu
12 min read