#K66117. Longest Substring with Exactly K Distinct Characters
Longest Substring with Exactly K Distinct Characters
Longest Substring with Exactly K Distinct Characters
Given a string s
and an integer k
, find the longest substring that contains exactly k
distinct characters. If there are multiple longest substrings satisfying this condition, return the one that appears first in s
. If no such substring exists, return an empty string.
Note: A substring is a contiguous sequence of characters within the string.
Examples:
- For
s = "abcba"
andk = 2
, the answer is"bcb"
. - For
s = "aaabbb"
andk = 3
, there is no valid substring, so the answer is""
(an empty string).
inputFormat
The input consists of two lines:
- The first line contains the string
s
. - The second line contains an integer
k
.
outputFormat
Output the longest substring from s
that contains exactly k
distinct characters. If there is no such substring, output an empty string.
abcba
2
bcb