Mirror Frequency Distance Problem
Description
LeetCode Problem 3889.
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 example, the mirror of
- 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 example, the mirror of
For each unique character c in the string:
- Let
mbe its mirror character. - Let
freq(x)denote the number of times characterxappears 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.
Example 1:
Input: s = "ab1z9"
Output: 3
Explanation:
For every mirror pair:
c m freq(c) freq(m) |freq(c) - freq(m)|
a z 1 1 0
b y 1 0 1
1 8 1 0 1
9 0 1 0 1
Thus, the answer is 0 + 1 + 1 + 1 = 3.
Example 2:
Input: s = "4m7n"
Output: 2
Explanation:
c m freq(c) freq(m) |freq(c) - freq(m)|
4 5 1 0 1
m n 1 1 0
7 2 1 0 1
Thus, the answer is 1 + 0 + 1 = 2.
Example 3:
Input: s = "byby"
Output: 0
Explanation:
c m freq(c) freq(m) |freq(c) - freq(m)|
b y 2 2 0
Thus, the answer is 0.
Constraints:
1 <= s.length <= 5 * 10^5sconsists only of lowercase English letters and digits.
Solution
Approach: Hash Table
Count how often each character occurs in s. Then go through the distinct characters c with count v, find the mirror m ('a'..'z' map to 'z'..'a', and digit d maps to 9 - d), and add |v - freq(m)|, treating a missing character as 0.
Each mirror pair must be counted once. Keep a set vis of characters already handled: if m is already in vis, the pair was counted when m was visited, so skip c; otherwise add c to vis and count the pair.
Complexity: time O(n), space O(1) (at most 36 distinct characters), where n is the length of s.
class Solution:
def mirrorFrequency(self, s: str) -> int:
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
ans = 0
vis = set()
for c, v in freq.items():
m = (
chr(ord("a") + 25 - (ord(c) - ord("a")))
if c.isalpha()
else str(9 - int(c))
)
if m in vis:
continue
vis.add(c)
ans += abs(v - freq.get(m, 0))
return ans