LeetCode in Kotlin

3889. Mirror Frequency Distance

Medium

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 each unique character c in the string:

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:

Solution

import kotlin.math.abs

class Solution {
    fun mirrorFrequency(s: String): Int {
        val freq = IntArray(257)
        val n = s.length
        for (i in 0..<n) {
            val curr = s[i]
            freq[curr.code]++
        }
        var ans = 0
        run {
            var i = 'a'.code
            while (i <= 'z'.code) {
                if (freq[i] > 0) {
                    ans += abs(freq[i] - freq['z'.code - (i - 'a'.code)])
                    freq[i] = 0
                    freq['z'.code - (i - 'a'.code)] = 0
                }
                i++
            }
        }
        var i = '0'.code
        while (i <= '9'.code) {
            if (freq[i] > 0) {
                ans += abs(freq[i] - freq['9'.code - (i - '0'.code)])
                freq[i] = 0
                freq['9'.code - (i - '0'.code)] = 0
            }
            i++
        }
        return ans
    }
}