Minimum Deletion Cost to Make All Characters Equal Problem
Description
LeetCode Problem 3784.
You are given a string s of length n and an integer array cost of the same length, where cost[i] is the cost to delete the i^th character of s.
You may delete any number of characters from s (possibly none), such that the resulting string is non-empty and consists of equal characters.
Return an integer denoting the minimum total deletion cost required.
Example 1:
Input: s = "aabaac", cost = [1,2,3,4,1,10]
Output: 11
Explanation:
Deleting the characters at indices 0, 1, 2, 3, 4 results in the string "c", which consists of equal characters, and the total cost is cost[0] + cost[1] + cost[2] + cost[3] + cost[4] = 1 + 2 + 3 + 4 + 1 = 11.
Example 2:
Input: s = "abc", cost = [10,5,8]
Output: 13
Explanation:
Deleting the characters at indices 1 and 2 results in the string "a", which consists of equal characters, and the total cost is cost[1] + cost[2] = 5 + 8 = 13.
Example 3:
Input: s = "zzzzz", cost = [67,67,67,67,67]
Output: 0
Explanation:
All characters in s are equal, so the deletion cost is 0.
Constraints:
n == s.length == cost.length1 <= n <= 10^51 <= cost[i] <= 10^9sconsists of lowercase English letters.
Solution
Approach: Keep One Letter
The string must end up with a single repeated letter, so we pick the letter to keep and delete everything else. Keeping a letter means keeping all of its occurrences, because deleting one of them only adds cost.
Sum the deletion costs per letter in a table, and also the total cost of all characters. If we keep letter c, we pay total - cost_of_c. The answer is the smallest of these values over the letters that appear in s.
Complexity: O(n) time and O(1) extra space (at most 26 letters).
from collections import defaultdict
class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
tot = 0
g = defaultdict(int)
for c, v in zip(s, cost):
tot += v
g[c] += v
return min(tot - x for x in g.values())