LeetCode in Kotlin

2068. Check Whether Two Strings are Almost Equivalent

Easy

Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.

Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.

The frequency of a letter x is the number of times it occurs in the string.

Example 1:

Input: word1 = “aaaa”, word2 = “bccb”

Output: false

Explanation: There are 4 ‘a’s in “aaaa” but 0 ‘a’s in “bccb”.

The difference is 4, which is more than the allowed 3.

Example 2:

Input: word1 = “abcdeef”, word2 = “abaaacc”

Output: true

Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:

Example 3:

Input: word1 = “cccddabba”, word2 = “babababab”

Output: true

Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:

Constraints:

Solution

import kotlin.math.abs

class Solution {
    fun checkAlmostEquivalent(word1: String, word2: String): Boolean {
        val freq = IntArray(26)
        for (i in word1.indices) {
            ++freq[word1[i].code - 'a'.code]
            --freq[word2[i].code - 'a'.code]
        }
        for (i in freq) {
            if (abs(i) > 3) {
                return false
            }
        }
        return true
    }
}