#2516
Take K of Each Character From Left and Right
MediumHash TableStringSliding WindowHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a sliding window technique to efficiently find the minimum number of characters needed to satisfy the k requirement for each character. This reduces the need for nested loops and improves performance.
⚙️
Algorithm
5 steps- 1Step 1: Count the frequency of 'a', 'b', and 'c' in the string s.
- 2Step 2: If any character's count is less than k, return -1 immediately.
- 3Step 3: Use two pointers to represent the left and right ends of the string. Start with both pointers at the ends and move them inward while counting characters.
- 4Step 4: Maintain a count of characters taken from both ends and check if the counts meet the requirement of at least k for each character.
- 5Step 5: Update the minimum time taken whenever the requirement is met.
solution.py24 lines
1def minMinutes(s, k):
2 count = {'a': 0, 'b': 0, 'c': 0}
3 for char in s:
4 count[char] += 1
5 if count['a'] < k or count['b'] < k or count['c'] < k:
6 return -1
7 left, right = 0, len(s) - 1
8 total = 0
9 while left <= right:
10 total += 1
11 if s[left] == 'a': count['a'] -= 1
12 elif s[left] == 'b': count['b'] -= 1
13 else: count['c'] -= 1
14 left += 1
15 if all(v <= 0 for v in (count['a'] - k, count['b'] - k, count['c'] - k)):
16 return total
17 total += 1
18 if s[right] == 'a': count['a'] -= 1
19 elif s[right] == 'b': count['b'] -= 1
20 else: count['c'] -= 1
21 right -= 1
22 if all(v <= 0 for v in (count['a'] - k, count['b'] - k, count['c'] - k)):
23 return total
24 return -1ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once with two pointers, making it much more efficient than the brute force approach.
- 1You must check if it's possible to meet the requirement before proceeding.
- 2Using a sliding window can significantly reduce the time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.