Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Create a string with unique characters from the given N substrings
Next article icon

Longest substring with k unique characters

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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. 

Table of Content

  • [Naive Approach] – Generate all Substring – O(n^2) Time and O(n) Space
  • [Expected Approach] – Sliding window with Array – O(n) Time and O(1) Space
  • [Alternate Approach] Sliding window with Unodered_map – O(n) Time and O(1) Space

[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)); 

Output
7

[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)); 

Output
7 

[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)); 

Output
7 


Next Article
Create a string with unique characters from the given N substrings

G

Gaurav Sharma
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
  • Amazon
  • Google
  • SAP Labs
Practice Tags :
  • Amazon
  • Google
  • SAP Labs
  • Hash
  • Strings

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:
    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" Expla
    5 min read
  • Find minimum number of Substrings with unique characters
    Given string 's', the task is to divide a given string s into multiple substrings, with each substring containing only unique characters. This means that no character should be repeated within a single substring. The goal is to find the minimum number of such substrings required to satisfy this cond
    12 min read
  • Create a string with unique characters from the given N substrings
    Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property p
    11 min read
  • Count substrings with k distinct characters
    Given a string 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 = 2Outp
    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:
    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
  • Count K-Length Substrings With No Repeated Characters
    Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters. Example: Input: S = "geeksforgeeks", k = 5Output: 4Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'. Input: S = "home", k = 5Output: 0Expla
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences