Skip to main content
Back to problems
#3223
Medium Algorithms

Minimum length of string after operations

Hash Table String Counting
75.0% acceptance
Feb 25, 2026
727
53
You are given a string s. You can perform the following process on s any number of times: Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i]. Delete the closest occurrence of s[i] located to the left of i. Delete the closest occurrence of s[i] located to the right of i. Return the minimum length of the final string s that you can achieve.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_length(s: String) -> i32 {
    let mut count = [0i32; 26];
    for b in s.bytes() {
      count[(b - b'a') as usize] += 1;
    }
    // If count is odd: keep 1; if count is even: keep 2
    count.iter().map(|&c| if c == 0 { 0 } else if c % 2 == 1 { 1 } else { 2 }).sum()
  }
}