Take K of Each Character From Left and Right

You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.

Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.

Example 1
Inputs = "aabaaaacaabc", k = 2
Output8
Taking three characters from the left and five from the right gives at least two of each character in 8 total minutes, which is the minimum possible.
Example 2
Inputs = "a", k = 1
Output-1
It is not possible to take one 'b' or 'c', so return -1.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only the letters 'a', 'b', and 'c'.
  • 0 <= k <= s.length

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate