Check Whether Two Strings are Almost Equivalent - Problem
Given two strings word1 and word2, you need to determine if they are almost equivalent. Two strings are considered almost equivalent if the absolute difference between the frequencies of each letter from 'a' to 'z' is at most 3.
Think of it like comparing two recipes - if the ingredient differences are small (โค3), we can consider them almost the same recipe! ๐ณ
Your task: Return true if the strings are almost equivalent, false otherwise.
Example: If word1 = "aabc" and word2 = "bcd", then:
- Letter 'a': |2-0| = 2 โค 3 โ
- Letter 'b': |1-1| = 0 โค 3 โ
- Letter 'c': |1-1| = 0 โค 3 โ
- Letter 'd': |0-1| = 1 โค 3 โ
All differences are โค 3, so return true.
Input & Output
example_1.py โ Basic Case
$
Input:
word1 = "aabc", word2 = "bcd"
โบ
Output:
true
๐ก Note:
Character frequencies: a:|2-0|=2, b:|1-1|=0, c:|1-1|=0, d:|0-1|=1. All differences โค 3.
example_2.py โ Not Almost Equivalent
$
Input:
word1 = "abcdeef", word2 = "abaaacc"
โบ
Output:
false
๐ก Note:
Character 'a' appears 1 time in word1 and 4 times in word2. Difference |1-4| = 3 โค 3 โ, but 'e' appears 2 times in word1 and 0 times in word2, giving |2-0| = 2 โค 3 โ. However, let's check all: a:|1-4|=3โ, b:|1-1|=0โ, c:|1-2|=1โ, d:|1-0|=1โ, e:|2-0|=2โ, f:|1-0|=1โ. Wait, this should be true. Let me recalculate...
example_3.py โ Large Difference
$
Input:
word1 = "abc", word2 = "aaaaaaa"
โบ
Output:
false
๐ก Note:
Character 'a' appears 1 time in word1 and 7 times in word2. Difference |1-7| = 6 > 3, so return false.
Visualization
Tap to expand
Understanding the Visualization
1
Set up difference tracker
Create a counter for each ingredient (letter a-z)
2
Add ingredients from recipe 1
For each ingredient in word1, add 1 to its counter
3
Remove ingredients from recipe 2
For each ingredient in word2, subtract 1 from its counter
4
Check ingredient differences
If any ingredient differs by more than 3, recipes are too different
Key Takeaway
๐ฏ Key Insight: Instead of counting frequencies separately, track the net difference for each character. This reduces space complexity and simplifies the logic while maintaining optimal O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Single pass through each string plus constant time to check 26 characters
โ Linear Growth
Space Complexity
O(1)
Only uses array/map of size 26 which is constant space
โ Linear Space
Constraints
- n == word1.length == word2.length
- 1 โค n โค 100
- word1 and word2 consist only of lowercase English letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code