[LeetCode] Mirror Frequency Distance

3889. Mirror Frequency Distance

You are given a string s consisting of lowercase English letters and digits.

For each character, its mirror character is defined by reversing the order of its character set:

  • For letters, the mirror of a character is the letter at the same position from the end of the alphabet.
    • For example, the mirror of 'a' is 'z', and the mirror of 'b' is 'y', and so on.
  • For digits, the mirror of a character is the digit at the same position from the end of the range '0' to '9'.
    • For example, the mirror of '0' is '9', and the mirror of '1' is '8', and so on.

For each unique character c in the string:

  • Let m be its mirror character.
  • Let freq(x) denote the number of times character x appears in the string.
  • Compute the absolute difference between their frequencies, defined as: |freq(c) - freq(m)|

The mirror pairs (c, m) and (m, c) are the same and must be counted only once.

Return an integer denoting the total sum of these values over all such distinct mirror pairs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class Solution {
int helper(vector<int>& A) {
int l = 0, r = A.size() - 1, res = 0;
while(l < r) res += abs(A[l++] - A[r--]);
return res;
}
public:
int mirrorFrequency(string s) {
vector<int> alpha(26), digit(10);
for(auto& ch : s) {
if(isalpha(ch)) alpha[ch-'a']++;
else digit[ch-'0']++;
}
return helper(alpha) + helper(digit);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/mirror-frequency-distance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.