Leetcode 2068. Check Whether Two Strings are Almost Equivalent
Given two strings word1 and word2, a string word1 is almost equivalent to word2 if the differences between the frequencies of each character from a to z between word1 and word2 is at most 3. Formally, for all characters c, |frequency(c, word1) - frequency(c, word2)| <= 3.
Return true if word1 and word2 are almost equivalent, otherwise, return false.
word1 and word2.false.word1 and word2.O(n), where n is the length of the longest string since the counting is done in a single pass through each string.#include <iostream>
#include <vector>
#include <cmath> // for abs
bool checkAlmostEquivalent(std::string word1, std::string word2) {
std::vector<int> freq1(26, 0); // Frequency array for word1
std::vector<int> freq2(26, 0); // Frequency array for word2
// Count character frequencies for word1
for(char c : word1) {
freq1[c - 'a']++;
}
// Count character frequencies for word2
for(char c : word2) {
freq2[c - 'a']++;
}
// Check the absolute difference in frequencies
for(int i = 0; i < 26; i++) {
if(std::abs(freq1[i] - freq2[i]) > 3) {
return false;
}
}
return true;
}
int main() {
std::string word1 = "aabbcc";
std::string word2 = "abbbccc";
bool result = checkAlmostEquivalent(word1, word2);
std::cout << (result ? "True" : "False") << std::endl;
return 0;
}
freq1 and freq2 to keep track of the frequencies of characters in word1 and word2.word1 and word2, updating the respective frequency array.false.true.The time complexity of this solution is O(n + m), where n is the length of word1 and m is the length of word2. This is because:
O(n) for word1 and O(m) for word2).O(26) or simply O(1).In conclusion, the overall complexity is linear with respect to the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?