Shortest Substring Containing Exactly K Distinct Characters
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Overview: A string coding problem: given a string and an integer k, return the shortest contiguous substring with exactly k distinct characters, preferring the earliest one on ties and returning an empty string when none exists. It tests efficient substring search on inputs of up to 100,000 characters.
Read the full Meta Software Engineer interview experience this question came from
Constraints
- 1 <= len(s) <= 10^5
- s consists of printable ASCII characters (codes 32 to 126).
- 1 <= k <= 10^5
Examples
Input: ('a', 1)
Expected Output: 'a'
Explanation: Minimum input: one character with k = 1 is its own answer.
Input: ('aaaa', 1)
Expected Output: 'a'
Explanation: One repeated character with k = 1: every one-character substring qualifies and index 0 wins.
Hints
- A substring with exactly k distinct characters has at least k characters, and one can exist only when s holds at least k distinct characters in total.
- Fix the end of a substring and move its start to the right: think about how the distinct-character count changes along the way.
- Several substrings can share the minimum length; keep the one that starts earliest.