Take K of Each Character From Left and Right

Medium Topics Company Tags

Each minute, remove either the first or the last remaining character of s and keep it. Return the fewest minutes needed to collect at least k copies of each of a, b, and c. Return -1 if this is impossible.

Example 1:

Input: s = "abccba"
k = 1

Output: 3

Explanation: Taking the first three characters collects a, b, and c in three minutes. At least three removals are needed to collect three different letters.

Example 2:

Input: s = "abc"
k = 0

Output: 0

Explanation: With k = 0, no characters need to be collected. The answer is zero minutes.

Example 3:

Input: s = "aabb"
k = 1

Output: -1

Explanation: The string contains no c. Collecting one of each letter is impossible, even after taking the entire string.

Constraints:

  • 1 <= s.length <= 100000
  • s contains only a, b, and c.
  • 0 <= k <= s.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.