VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-longest-substring-with-k-unique-characters-in-a-given-string/

⇱ Longest substring with k unique characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest substring with k unique characters

Last Updated : 14 Mar, 2026

Given a string s and a non negative integer k, find the length of the longest substring that contains exactly k distinct characters. If no such substring exists, return -1.

Examples: 

Input: s = "aabacbebebe", k = 3
Output: 7
Explanation: The longest substring with exactly 3 distinct characters is "cbebebe", which includes 'c', 'b', and 'e'.

Input: s = "aaaa", k = 2
Output: -1
Explanation: The string contains only one unique character, so there's no substring with 2 distinct characters.

Input: s = "aabaaab", k = 2
Output: 7
Explanation: The entire string "aabaaab" has exactly 2 unique characters 'a' and 'b', making it the longest valid substring.

[Naive Approach] Using nested loops with a hash set - O(n^2) Time and O(1) Space

This brute-force approach checks all substrings starting from each index. It uses a set to track unique characters, and whenever a substring has exactly k distinct characters, it updates the maximum length.


Output
7

[Better Approach] Using Prefix Sum and Binary Search - O(n*log n) Time and O(n) Space

  • Build a prefix frequency table to store how many times each character appears up to every position.
  • For each starting index, use binary search to find the farthest end index where the substring has exactly k unique characters.
  • Use the prefix table differences to quickly count distinct characters in the substring.

Output
7

[Expected Approach] Sliding Window with Frequency Count - O(n) Time and O(1) Space

  • Use a sliding window with two pointers (i and j) to represent the start and end of the current substring.
  • Maintain a frequency array and a counter to track the number of unique characters in the window.
  • Expand the window by moving j, and if unique characters exceed k, shrink the window from the left by moving i.
  • Whenever the window contains exactly k unique characters, update the maximum substring length.

Output
7
Comment
Article Tags: