Longest Substring with K Unique Characters
Problem Statement
You are given a string s of lowercase letters and a number k.
Find the longest substring (contiguous part of s) that contains exactly k different letters. Return its length.
If no substring has exactly k different letters, return −1.
The function is longestKSubstr(s, k) and returns an int.
A string s of lowercase English letters and an integer k.
The length of the longest substring with exactly k distinct letters, or -1 if there is none.
"cbebebe" uses exactly 3 letters (c, b, e) and has length 7. No longer substring has exactly 3 letters.
The whole string only has 1 distinct letter, so no substring can have exactly 2.
The whole string uses exactly 2 letters (a and b).
- • 1 ≤ s.length ≤ 10^5
- • 1 ≤ k ≤ 26
- • s contains only lowercase English letters
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, extend right while tracking distinct letters
Grow right; shrink while distinct > k; record length only when distinct == k
Try every starting index. From each start, extend the end one letter at a time, keeping a count array and the number of distinct letters. Whenever distinct is exactly k, record the length. Once distinct goes above k, stop — growing can't bring it back down.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.