Skip to main content
Back to problems
#3412
Medium Algorithms

Find mirror score of a string

Hash Table String Stack Simulation
35.4% acceptance
Feb 25, 2026
124
8
You are given a string s. We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a' is 'z', and the mirror of 'y' is 'b'. Initially, all characters in the string s are unmarked. You start with a score of 0, and you perform the following process on the string s: Iterate through the string from left to right. At each index i, find the closest unmarked index j such that j < i and s[j] is the mirror of s[i]. Then, mark both indices i and j, and add the value i - j to the total score. If no such index j exists for the index i, move on to the next index without making any changes. Return the total score at the end of the process.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn calculate_score(s: String) -> i64 {
    let bytes = s.as_bytes();
    let mut stacks: Vec<Vec<usize>> = vec![Vec::new(); 26];
    let mut score = 0i64;
    for (i, &c) in bytes.iter().enumerate() {
      let idx = (c - b'a') as usize;
      let mirror = 25 - idx;
      if let Some(j) = stacks[mirror].pop() {
        score += (i - j) as i64;
      } else {
        stacks[idx].push(i);
      }
    }
    score
  }
}