#2068

Check Whether Two Strings are Almost Equivalent

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

By using a frequency count with a single pass for each string, we can efficiently determine the differences without redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a frequency array of size 26 to count occurrences of each character in both strings.
  2. 2Step 2: For each character, calculate the absolute difference in frequency counts.
  3. 3Step 3: If any difference exceeds 3, return false. If all differences are within 3, return true.
solution.py11 lines
1# Full working Python code
2def areAlmostEquivalent(word1, word2):
3    count = [0] * 26
4    for c in word1:
5        count[ord(c) - ord('a')] += 1
6    for c in word2:
7        count[ord(c) - ord('a')] -= 1
8    for freq in count:
9        if abs(freq) > 3:
10            return False
11    return True

Complexity note: The time complexity is O(n) since we only traverse each string once. The space complexity is O(1) because the frequency array size is constant (26 for the alphabet).

  • 1Using frequency counts allows for efficient comparison of character occurrences.
  • 2The absolute difference check is crucial for determining equivalence.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.