#K66117. Longest Substring with Exactly K Distinct Characters

    ID: 32350 Type: Default 1000ms 256MiB

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" and k = 2, the answer is "bcb".
  • For s = "aaabbb" and k = 3, there is no valid substring, so the answer is "" (an empty string).

inputFormat

The input consists of two lines:

  1. The first line contains the string s.
  2. 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.

## sample
abcba
2
bcb