[LeetCode]#2068. Check Whether Two Strings are Almost Equivalent

Fatboy Slim
2 min readDec 24, 2021

Environment: Python 3.8

Key technique: Counter, |, max

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.

Analysis:

  1. use Counter to word1 and word2
  2. Find their different
  3. Find their union
  4. If value ≤3, return True

Solution:

class Solution:
def checkAlmostEquivalent(self, word1, word2):
c1, c2 = Counter(word1), Counter(word2)
values = ((c1-c2)|(c2-c1)).values()
return max(values, default=0) < 4

Note: default=0 is for a special case.

Submissions:

Reference:

https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1609184/Python3-elegant-solution-using-two-counters

--

--