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: true
💡 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 the strings are almost equivalent.
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
Almost Equivalent Strings Checker INPUT word1 = "aabc" a a b c word2 = "aabb" a a b b Character Frequencies: word1 a:2, b:1, c:1 others: 0 word2 a:2, b:2 others: 0 n = 4 (length) threshold = 3 ALGORITHM STEPS 1 Initialize diff array Create array[26] = all 0s 2 Single pass scan For each index i: diff[word1[i]]++ diff[word2[i]]-- 3 Check differences For each letter a-z: if |diff[i]| > 3 return false Difference Tracking: a: 2-2 = 0 |0| <= 3 OK b: 1-2 = -1 |-1| <= 3 OK c: 1-0 = 1 |1| <= 3 OK 4 Return result All diffs <= 3: true FINAL RESULT true Almost Equivalent All Differences Summary: Letter | Diff | Status a 0 OK b -1 OK c 1 OK Max |diff| = 1 <= 3 Output: true Key Insight: Single pass approach: Track frequency differences in one array using increment for word1 and decrement for word2. Final check ensures all absolute differences are at most 3. Time: O(n + 26) = O(n) | Space: O(26) = O(1) - Only need fixed-size alphabet array. TutorialsPoint - Check Whether Two Strings are Almost Equivalent | Single Pass Difference Tracking
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