Skip to main content
Back to problems
#3784
Medium Algorithms

Minimum deletion cost to make all characters equal

Array Hash Table String Enumeration
55.0% acceptance
Feb 25, 2026
87
9
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 ith 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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_cost(s: String, cost: Vec<i32>) -> i64 {
    let bytes = s.as_bytes();
    let n = bytes.len();
    let total: i64 = cost.iter().map(|&c| c as i64).sum();
    (b'a'..=b'z').map(|c| {
      // Cost to keep only character c: sum of cost[i] where bytes[i] != c
      let keep: i64 = (0..n).filter(|&i| bytes[i] == c).map(|i| cost[i] as i64).sum();
      total - keep
    }).min().unwrap()
  }
}