Given two strings word1
and word2
, they are considered almost equivalent if the following condition is satisfied:
For every character ch
in the set of characters of word1
∪ word2
, the absolute difference between the number of occurrences of ch
in word1
and word2
is at most 3
.
Return true
if word1
and word2
are almost equivalent, or false
otherwise.
word1
and word2
?
word1
and word2
are not specified, but usual constraints for string problems like this on LeetCode fall within a manageable range for algorithms needing O(n) time complexity.collections.Counter
.word1
and word2
.3
, return false
.true
.from collections import Counter
def checkAlmostEquivalent(word1: str, word2: str) -> bool:
# Count character frequencies for both words
counter1 = Counter(word1)
counter2 = Counter(word2)
# Get the union of keys from both counters
all_chars = set(counter1.keys()).union(set(counter2.keys()))
# Check the absolute difference for each character
for ch in all_chars:
if abs(counter1.get(ch, 0) - counter2.get(ch, 0)) > 3:
return False
return True
# Example usage
word1 = "acbdeab"
word2 = "abcdedcbf"
print(checkAlmostEquivalent(word1, word2)) # Output: True
n
is the length of word1
and m
is the length of word2
.u
is the total number of unique characters from both strings combined. However, u is at most 26 for lowercase letters in the Latin alphabet.Counter
objects to store the frequency of each character in word1
and word2
, which will each require space proportional to the number of unique characters, resulting in a space complexity of O(u).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?