2516. Take K of Each Character From Left and Right #855
-
Topics: You are given a string Return the minimum number of minutes needed for you to take at least Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a sliding window technique with two pointers to find the minimum number of minutes needed to take at least Problem Breakdown:
Approach:
Let's implement this solution in PHP: 2516. Take K of Each Character From Left and Right <?php
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function takeCharacters($s, $k) {
$n = strlen($s); // Length of the string
$ans = $n;
$count = [0, 0, 0]; // To count occurrences of 'a', 'b', 'c'
// Count occurrences of each character
for ($i = 0; $i < $n; $i++) {
$count[ord($s[$i]) - ord('a')]++;
}
// If any character count is less than k, return -1
if ($count[0] < $k || $count[1] < $k || $count[2] < $k) {
return -1;
}
// Sliding window approach
$l = 0; // Left pointer
for ($r = 0; $r < $n; $r++) { // Right pointer
$count[ord($s[$r]) - ord('a')]--;
while ($count[ord($s[$r]) - ord('a')] < $k) {
$count[ord($s[$l]) - ord('a')]++;
$l++;
}
$ans = min($ans, $n - ($r - $l + 1));
}
return $ans;
}
// Example 1
echo takeCharacters("aabaaaacaabc", 2); // Output: 8
// Example 2
echo takeCharacters("a", 1); // Output: -1
?> Explanation:
Time Complexity:
Edge Cases:
|
Beta Was this translation helpful? Give feedback.
We can use a sliding window technique with two pointers to find the minimum number of minutes needed to take at least
k
of each character ('a', 'b', 'c') from both the left and right of the string.Problem Breakdown:
s
containing only 'a', 'b', and 'c'.k
occurrences of each character, either from the leftmost or rightmost characters of the string.-1
if it's impossible.Approach:
Initial Checks:
k == 0
, we can directly return0
since no characters are required.k
exceeds the number of occurrences of any character in the string, return-1
immediat…