Skip to content

2516. Take K of Each Character From Left and Right

Difficulty Topics

Description

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:

Input: s = "aabaaaacaabc", k = 2
Output: 8
Explanation: 
Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.
Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.
A total of 3 + 5 = 8 minutes is needed.
It can be proven that 8 is the minimum number of minutes needed.

Example 2:

Input: s = "a", k = 1
Output: -1
Explanation: It is not possible to take one 'b' or 'c' so return -1.

 

Constraints:

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

Solution

take-k-of-each-character-from-left-and-right.py
class Solution:
    def takeCharacters(self, s: str, target: int) -> int:
        N = len(s)

        prefix = [[0, 0, 0]]
        for x in s:
            a, b, c = prefix[-1]

            if x == "a":
                a += 1
            elif x == "b":
                b += 1
            else:
                c += 1

            prefix.append([a, b, c])

        def query(i, j):
            la, lb, lc = prefix[i]
            ra, rb, rc = prefix[j]

            return [ra - la, rb - lb, rc - lc]

        def good(k):
            for i in range(k + 1):
                la, lb, lc = query(0, i)
                ra, rb, rc = query(N - k + i, N)

                a, b, c = la + ra, lb + rb, lc + rc

                if a >= target and b >= target and c >= target:
                    return True

            return False

        res = -1
        left, right = 3 * target, N

        while left <= right:
            mid = left + (right - left) // 2

            if good(mid):
                res = mid
                right = mid - 1
            else:
                left = mid + 1

        return res