Sum of Mirror Frequency Differences

You are given a string s containing only lowercase English letters and digits.

For any character, its mirror character is defined as follows:

For lowercase letters, the mirror is the letter at the same position from the end of the alphabet.

  • 'a' <-> 'z', 'b' <-> 'y', 'c' <-> 'x', ...

For digits, the mirror is the digit at the same position from the end of '0' to '9'.

  • '0' <-> '9', '1' <-> '8', '2' <-> '7', ...

Let freq(x) be the number of times character x appears in the string.

For every distinct mirror pair (c, m), compute: |freq(c) - freq(m)|

Each mirror pair must be counted only once. For example, (a, z) and (z, a) represent the same pair.

Return the total sum of these values over all distinct mirror pairs that involve at least one character present in the string.

Example 1:

Input: s = "azb8"

Output: 2

Explanation:

The distinct mirror pairs involved are:

  • (a, z) โ†’ |1 - 1| = 0
  • (b, y) โ†’ |1 - 0| = 1
  • (8, 1) โ†’ |1 - 0| = 1

So, the total sum is 0 + 1 + 1 = 2.

Example 2:

Input: s = "ccxx30"

Output: 2

Explanation:

The distinct mirror pairs involved are:

  • (c, x) โ†’ |2 - 2| = 0
  • (3, 6) โ†’ |1 - 0| = 1
  • (0, 9) โ†’ |1 - 0| = 1

So, the total sum is 0 + 1 + 1 = 2.

Now Your Turn!

Pick the correct output for the given input

Input: s = "a0z2"

Still unsure what the problem is asking ?

Letโ€™s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= s.length <= 5 * 105
  • s consists only of: lowercase English letters ('a' to 'z'), digits ('0' to '9')

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int mirrorFrequency(string s) {
// Your code goes here
}
};
Test Case

Input:

S