Check Whether Two Strings are Almost Equivalent — LeetCode 2068 Python Solution
- Problem
- #2068
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- word1 = "aaaa", word2 = "bccb"
- Output
- false
- Explanation
- There are 4 'a's in "aaaa" but 0 'a's in "bccb".
Python solution
class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
cnt = Counter(word1)
for c in word2:
cnt[c] -= 1
return all(abs(x) <= 3 for x in cnt.values())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2068. Check Whether Two Strings are Almost Equivalent is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2068. Check Whether Two Strings are Almost Equivalent?
- LeetCode 2068. Check Whether Two Strings are Almost Equivalent is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2068. Check Whether Two Strings are Almost Equivalent?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2068. Check Whether Two Strings are Almost Equivalent?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 2068. Check Whether Two Strings are Almost Equivalent cover?
- LeetCode 2068. Check Whether Two Strings are Almost Equivalent is tagged Hash Table, String and Counting on LeetCode.