Table of Contents
Description Check Whether Two Strings are Almost Equivalent
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.
Example 1
1 2 3 4 |
<strong>Input:</strong> word1 = "aaaa", word2 = "bccb" <strong>Output:</strong> false <strong>Explanation:</strong> There are 4 'a's in "aaaa" but 0 'a's in "bccb". The difference is 4, which is more than the allowed 3. |
Example 2
1 2 3 4 5 6 7 8 9 |
<strong>Input:</strong> word1 = "abcdeef", word2 = "abaaacc" <strong>Output:</strong> true <strong>Explanation:</strong> The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 1 time in word1 and 4 times in word2. The difference is 3. - 'b' appears 1 time in word1 and 1 time in word2. The difference is 0. - 'c' appears 1 time in word1 and 2 times in word2. The difference is 1. - 'd' appears 1 time in word1 and 0 times in word2. The difference is 1. - 'e' appears 2 times in word1 and 0 times in word2. The difference is 2. - 'f' appears 1 time in word1 and 0 times in word2. The difference is 1. |
Example 3
1 2 3 4 5 6 7 |
<strong>Input:</strong> word1 = "cccddabba", word2 = "babababab" <strong>Output:</strong> true <strong>Explanation:</strong> The differences between the frequencies of each letter in word1 and word2 are at most 3: - 'a' appears 2 times in word1 and 4 times in word2. The difference is 2. - 'b' appears 2 times in word1 and 5 times in word2. The difference is 3. - 'c' appears 3 times in word1 and 0 times in word2. The difference is 3. - 'd' appears 2 times in word1 and 0 times in word2. The difference is 2. |
Constraints
n == word1.length == word2.length
1 <= n <= 100
word1
andword2
consist only of lowercase English letters.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Solution { public boolean checkAlmostEquivalent(String word1, String word2) { if(word1==null && word2==null){ return true; } if(word1==null || word2==null){ return false; } int[] f1 = getFreq(word1); int[] f2 = getFreq(word2); for(int i=0;i<f1.length;i++){ if(Math.abs(f1[i]-f2[i])>3){ return false; } } return true; } private int[] getFreq(String a){ int[] freq = new int[26]; for(int i=0;i<a.length();i++){ freq[a.charAt(i)-'a']++; } return freq; } } |
Time Complexity
O(n), where n is the length of words
Space Complexity
O(26 * 2) -> O(1), constant space