Longest Substring with K Distinct Characters
Given a string s and a non-negative integer k, find the length of the longest substring that contains exactly k distinct characters. Return -1 if no such substring exists.
Asked at:
Question Timeline
See when this question was last asked and where, including any notes left by other candidates.
Early July, 2026
Mid-level
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.
Hello Interview Premium
Your account is free and you can post anonymously if you choose.