Skip to main content
Back to problems
#2068
Easy Algorithms

Check whether two strings are almost equivalent

Hash Table String Counting
64.1% acceptance
Feb 25, 2026
574
23
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn check_almost_equivalent(word1: String, word2: String) -> bool {
    let mut freq = [0i32; 26];
    for b in word1.bytes() { freq[(b - b'a') as usize] += 1; }
    for b in word2.bytes() { freq[(b - b'a') as usize] -= 1; }
    freq.iter().all(|&f| f.abs() <= 3)
  }
}