Ctrl K

Collecting a, b and c From Both Ends

Medium
You get a string letters made of the characters a, b and c, and a non-negative integer need. In one move you remove either the leftmost or the rightmost character of the string and keep it. Return the smallest number of moves after which you hold at least need copies of each of the three letters. If that cannot happen, return -1.
Example 1
letters="cabbacca", need=1 → 3

Take c, a, b from the left: three letters, and we already hold one of each. Fewer is impossible, since we need at least three letters.

Example 2
letters="abaacbc", need=2 → 6

Two letters from the left (a, b) and three from the right (c, b, c) give two bs and two cs but just one a, so one more from the left is needed: 6 in total.

Example 3
letters="aabba", need=1 → -1

There is no c in the string at all, so the answer is -1.

Constraints
  • 1 ≤ len(letters) ≤ 10⁵
  • letters contains only a, b and c
  • 0 ≤ need ≤ len(letters)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Repeat-Free Stretch MediumTwo-Letter Stretch MediumRecurring Gene Windows MediumWindow with Few Kinds of Letters MediumEvery Letter at Least k Times Medium
loading Python…
Input
letters="cabbacca", need=1
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 128 tests on the server, hidden ones included.