LeetCode 2068: Check Whether Two Strings are Almost Equivalent Solution
Master LeetCode problem 2068 (Check Whether Two Strings are Almost Equivalent), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2068. Check Whether Two Strings are Almost Equivalent
Problem Explanation
Explanation:
To check whether two strings are almost equivalent, we need to calculate the frequency of each letter in both strings and ensure that the difference in frequencies for each letter is at most 3. We can achieve this by iterating over both strings simultaneously and comparing the frequencies of corresponding letters.
- Initialize two arrays of size 26 to store the frequencies of letters for both strings.
- Iterate over both strings simultaneously and update the frequency arrays.
- Compare the frequencies of corresponding letters and check if the absolute difference is at most 3.
- If the difference exceeds 3 for any letter, return false. Otherwise, return true.
Time Complexity: O(n), where n is the length of the strings.
Space Complexity: O(1) since we are using constant space to store frequencies for 26 lowercase letters.
Solution Code
class Solution {
public boolean areAlmostEquivalent(String word1, String word2) {
if (word1.length() != word2.length()) {
return false;
}
int[] freq1 = new int[26];
int[] freq2 = new int[26];
for (int i = 0; i < word1.length(); i++) {
freq1[word1.charAt(i) - 'a']++;
freq2[word2.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (Math.abs(freq1[i] - freq2[i]) > 3) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2068 (Check Whether Two Strings are Almost Equivalent)?
This page provides optimized solutions for LeetCode problem 2068 (Check Whether Two Strings are Almost Equivalent) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2068 (Check Whether Two Strings are Almost Equivalent)?
The time complexity for LeetCode 2068 (Check Whether Two Strings are Almost Equivalent) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2068 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2068 in Java, C++, or Python.