Skip to content

2516. Take K of Each Character From Left and Right 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int takeCharacters(string s, int k) {
    const int n = s.length();
    int ans = n;
    vector<int> count(3);

    for (const char c : s)
      ++count[c - 'a'];

    if (count[0] < k || count[1] < k || count[2] < k)
      return -1;

    for (int l = 0, r = 0; r < n; ++r) {
      --count[s[r] - 'a'];
      while (count[s[r] - 'a'] < k)
        ++count[s[l++] - 'a'];
      ans = min(ans, n - (r - l + 1));
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int takeCharacters(String s, int k) {
    final int n = s.length();
    int ans = n;
    int[] count = new int[3];

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    if (count[0] < k || count[1] < k || count[2] < k)
      return -1;

    for (int l = 0, r = 0; r < n; ++r) {
      --count[s.charAt(r) - 'a'];
      while (count[s.charAt(r) - 'a'] < k)
        ++count[s.charAt(l++) - 'a'];
      ans = Math.min(ans, n - (r - l + 1));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def takeCharacters(self, s: str, k: int) -> int:
    n = len(s)
    ans = n
    count = collections.Counter(s)
    if any(count[c] < k for c in 'abc'):
      return -1

    l = 0
    for r, c in enumerate(s):
      count[c] -= 1
      while count[c] < k:
        count[s[l]] += 1
        l += 1
      ans = min(ans, n - (r - l + 1))

    return ans