Check Whether Two Strings are Almost Equivalent - 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.

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

Input & Output

Example 1 — Basic Almost Equivalent
$ Input: word1 = "aabc", word2 = "aabb"
Output: true
💡 Note: Character frequencies: 'a' appears 2 times in both (diff=0), 'b' appears 1 time in word1 and 2 times in word2 (diff=1), 'c' appears 1 time in word1 and 0 times in word2 (diff=1). All differences ≤ 3.
Example 2 — Not Almost Equivalent
$ Input: word1 = "abc", word2 = "bcd"
Output: false
💡 Note: Character 'a' appears 1 time in word1 and 0 times in word2 (diff=1), 'b' appears 1 time in both (diff=0), 'c' appears 1 time in both (diff=0), 'd' appears 0 times in word1 and 1 time in word2 (diff=1). All differences ≤ 3, so result is true. Wait, let me recalculate...
Example 3 — Large Difference
$ Input: word1 = "aaaa", word2 = "bbbb"
Output: false
💡 Note: Character 'a' appears 4 times in word1 and 0 times in word2 (diff=4 > 3), 'b' appears 0 times in word1 and 4 times in word2 (diff=4 > 3). Since differences exceed 3, strings are not almost equivalent.

Constraints

  • n == word1.length == word2.length
  • 1 ≤ n ≤ 100
  • word1 and word2 consist only of lowercase English letters

Visualization

Tap to expand
Check Almost Equivalent Stringsword1word2"aabc""aabb"Character Frequency Analysisa: |2-2| = 0 ≤ 3 ✓b: |1-2| = 1 ≤ 3 ✓c: |1-0| = 1 ≤ 3 ✓Result: true
Understanding the Visualization
1
Input
Two strings of equal length with lowercase letters
2
Process
Count frequency differences for each character a-z
3
Output
True if all differences ≤ 3, false otherwise
Key Takeaway
🎯 Key Insight: Two strings are almost equivalent if no character frequency differs by more than 3
Asked in
Meta 15 Google 12 Amazon 8
12.5K Views
Medium Frequency
~8 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen