Minimum Operations to Make Character Frequencies Equal Problem
Description
LeetCode Problem 3389.
You are given a string s.
A string t is called good if all characters of t occur the same number of times.
You can perform the following operations any number of times:
- Delete a character from
s. - Insert a character in
s. - Change a character in
sto its next letter in the alphabet.
Note that you cannot change 'z' to 'a' using the third operation.
Return the minimum number of operations required to make s good.
Example 1:
Input: s = "acab"
Output: 1
Explanation:
We can make s good by deleting one occurrence of character 'a'.
Example 2:
Input: s = "wddw"
Output: 0
Explanation:
We do not need to perform any operations since s is initially good.
Example 3:
Input: s = "aaabc"
Output: 2
Explanation:
We can make s good by applying these operations:
- Change one occurrence of 'a' to 'b'
- Insert one occurrence of 'c' into s
Constraints:
3 <= s.length <= 2 * 10^4scontains only lowercase English letters.
Solution
Approach: Try every target frequency + DP over the alphabet
Fix a target frequency t: every letter that stays in the string must occur exactly t times, and the other letters occur zero times. Deleting or inserting one character costs 1, and so does changing a character to the next letter. Changing a surplus character of letter i - 1 into letter i (instead of deleting it) is useful only when letter i is short of copies, and it then saves one insertion.
Let f[i] be the cheapest cost for the first i letters. A letter is either handled alone (delete all its copies, or delete/insert to reach t copies), or is paired with the previous letter, whose surplus fills its shortage: the pair costs the two individual costs minus min(surplus, shortage). Take the best f[26] over all t from 1 to n.
Complexity: Time O(26 * n), space O(26).
class Solution:
def makeStringGood(self, s: str) -> int:
cnt = [0] * 26
for ch in s:
cnt[ord(ch) - 97] += 1
ans = len(s)
for t in range(1, len(s) + 1):
# f[i]: cost for the first i letters, every kept letter ends with exactly t copies
f = [0] * 27
for i in range(26):
f[i + 1] = f[i] + min(cnt[i], abs(cnt[i] - t))
if i > 0:
# surplus of letter i-1 can be changed into letter i to fill its shortage
x, y = cnt[i - 1], cnt[i]
shortage = max(0, t - y)
for keep in (False, True):
surplus = max(0, x - t) if keep else x
base = abs(x - t) if keep else x
f[i + 1] = min(f[i + 1], f[i - 1] + base + abs(y - t) - min(surplus, shortage))
ans = min(ans, f[26])
return ans