Quick 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.

Shortest Substring Containing Exactly K Distinct Characters

Company: Meta

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Technical Screen

Given a string `s` and an integer `k`, return the shortest contiguous substring of `s` that contains exactly `k` distinct characters. If several substrings have that minimum length, return the one that starts at the smallest index. If no substring of `s` contains exactly `k` distinct characters, return the empty string. ### Function Signature ```python def shortest_substring_with_k_distinct(s: str, k: int) -> str: ``` ### Rules - A substring is a contiguous slice `s[i:j]` with `i < j`. - The distinct-character count of a substring is the number of different characters in it. Characters are compared case-sensitively (`"a"` and `"A"` differ), and spaces and punctuation count as characters. - A substring qualifies only when its distinct-character count equals `k`. - Ties on length go to the smallest start index. - Return `""` when `s` has fewer than `k` distinct characters in total. ### Constraints - `1 <= len(s) <= 10^5` - `s` consists of printable ASCII characters (codes 32 to 126). - `1 <= k <= 10^5` ### Examples #### Example 1 ```text Input: s = "aabbcbbca", k = 3 Output: "bca" ``` The substring starting at index 6 holds `b`, `c` and `a`. Every length-3 substring that starts earlier has only two distinct letters, and no substring shorter than 3 can hold three distinct characters. #### Example 2 ```text Input: s = "xyzzyx", k = 3 Output: "xyz" ``` Both `"xyz"` (index 0) and `"zyx"` (index 3) have length 3, so the earlier one is returned. #### Example 3 ```text Input: s = "aaaa", k = 2 Output: "" ``` The string has only one distinct character.

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

Given a string `s` and an integer `k`, return the shortest contiguous substring of `s` that contains exactly `k` distinct characters. - A substring is a contiguous slice `s[i:j]` with `i < j`, so it is never empty. - The distinct-character count of a substring is the number of different characters in it. Characters are compared case-sensitively (`"a"` and `"A"` are different), and spaces and punctuation count as characters. - A substring qualifies only when its distinct-character count equals `k`. - If several qualifying substrings share the minimum length, return the one that starts at the smallest index. - If no substring has exactly `k` distinct characters, which happens exactly when `s` has fewer than `k` distinct characters in total, return the empty string `""`. Implement `shortest_substring_with_k_distinct(s, k)`. In every language `s` arrives as a string (`String` in Java, `const std::string&` in C++), `k` arrives as an `int`, and the result is a string. Lengths, indices and `k` all fit in a signed 32-bit integer. ### Example 1 ```text Input: s = "aabbcbbca", k = 3 Output: "bca" ``` The substring starting at index 6 holds `b`, `c` and `a`. Every length-3 substring that starts earlier has only two distinct letters, and no substring shorter than 3 can hold three distinct characters. ### Example 2 ```text Input: s = "xyzzyx", k = 3 Output: "xyz" ``` Both `"xyz"` (index 0) and `"zyx"` (index 3) have length 3, so the earlier one is returned. ### Constraints - `1 <= len(s) <= 10^5` - `s` consists of printable ASCII characters (codes 32 to 126). - `1 <= k <= 10^5`

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

  1. 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.
  2. Fix the end of a substring and move its start to the right: think about how the distinct-character count changes along the way.
  3. Several substrings can share the minimum length; keep the one that starts earliest.

Shortest Substring With Exactly K Distinct Characters

hardMetaSoftware Engineer

Given a string s and an integer k, return the shortest contiguous substring of s that contains exactly k distinct characters.

  • A substring is a contiguous slice s[i:j] with i < j, so it is never empty.
  • The distinct-character count of a substring is the number of different characters in it. Characters are compared case-sensitively ("a" and "A" are different), and spaces and punctuation count as characters.
  • A substring qualifies only when its distinct-character count equals k.
  • If several qualifying substrings share the minimum length, return the one that starts at the smallest index.
  • If no substring has exactly k distinct characters, which happens exactly when s has fewer than k distinct characters in total, return the empty string "".

Implement shortest_substring_with_k_distinct(s, k). In every language s arrives as a string (String in Java, const std::string& in C++), k arrives as an int, and the result is a string. Lengths, indices and k all fit in a signed 32-bit integer.

Example 1

Input:  s = "aabbcbbca", k = 3
Output: "bca"

The substring starting at index 6 holds b, c and a. Every length-3 substring that starts earlier has only two distinct letters, and no substring shorter than 3 can hold three distinct characters.

Example 2

Input:  s = "xyzzyx", k = 3
Output: "xyz"

Both "xyz" (index 0) and "zyx" (index 3) have length 3, so the earlier one is returned.

Constraints

  • 1 <= len(s) <= 10^5
  • s consists of printable ASCII characters (codes 32 to 126).
  • 1 <= k <= 10^5

Examples

Example 1
Input
('a', 1)
Output
'a'
Notes
Minimum input: one character with k = 1 is its own answer.
Example 2
Input
('aaaa', 1)
Output
'a'
Notes
One repeated character with k = 1: every one-character substring qualifies and index 0 wins.

Constraints

  • •1 <= len(s) <= 10^5
  • •s consists of printable ASCII characters (codes 32 to 126).
  • •1 <= k <= 10^5

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def shortest_substring_with_k_distinct(s: str, k: int) -> str:
Sample call
shortest_substring_with_k_distinct('a', 1)
Language
Case 1
Input
('a', 1)
Expected
'a'
Case 2
Input
('aaaa', 1)
Expected
'a'

Browse More Questions

Show the approach

Approach

Scan s once with a window s[left..right] and a count array indexed by character code. After adding s[right], move left forward while the window holds more than k distinct characters. If the window then holds exactly k distinct characters, keep moving left forward while the character at left occurs more than once in the window; each such step leaves the distinct count at k. The window is then the shortest substring that ends at right and has exactly k distinct characters, and it replaces the stored answer only when it is strictly shorter.

The scan keeps this invariant: once the prefix s[0..right] holds at least k distinct characters, left is the largest start for which s[left..right] still holds at least k distinct characters.

Correctness: for a fixed end, the distinct count of s[l..right] never grows as l increases, and it drops by at most one per step. So the largest start with at least k distinct characters has exactly k, and it gives the shortest qualifying substring for that end. Moving left forward never discards a start that a later end needs: for any later end, s[left..end] still holds at least k distinct characters, so its best start lies at or after left. A minimum-length answer is the shortest qualifying substring for its own end, so the scan reaches every one of them. Among equal lengths, a smaller start means a smaller end, and ends are visited in increasing order, so the strict comparison keeps the smallest start.

Edge cases: when s has fewer than k distinct characters (every k above 95 included), the count never reaches k and the answer is the empty string. With k = 1 the answer is the first character. Each pointer moves at most len(s) times, so the scan is linear, and the count array has a fixed size.

Time complexity:
O(n)
Space complexity:
O(1)