Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions 2068.check-whether-two-strings-are-almost-equivalent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* URL of this problem
* https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/description/
*
* @param {string} word1
* @param {string} word2
* @return {boolean}
*/

var checkAlmostEquivalent = function(word1, word2) {
const Word1CharsByFreq = new Map();
const Word2CharsByFreq = new Map();
const UniqueChars = [...new Set(word1 + word2)];
const MaximumFrequency = 3;

for (let i = 0; i < word1.length; i++) {
Word1CharsByFreq.set(word1[i], (Word1CharsByFreq.get(word1[i]) ?? 0) + 1);
Word2CharsByFreq.set(word2[i], (Word2CharsByFreq.get(word2[i]) ?? 0) + 1);
}
for (let i = 0; i < UniqueChars.length; i++) {
const Word1CharFreq = Word1CharsByFreq.get(UniqueChars[i]) ?? 0;
const Word2CharFreq = Word2CharsByFreq.get(UniqueChars[i]) ?? 0;
const Difference = Math.abs(Word1CharFreq - Word2CharFreq);

if (Difference > MaximumFrequency) {
return false;
}
}
return true;
};

module.exports = checkAlmostEquivalent;
13 changes: 13 additions & 0 deletions checkAlmostEquivalent.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const checkAlmostEquivalent = require("./2068.check-whether-two-strings-are-almost-equivalent");

test("Return true if word1 and word2 comprise the same letters and frequency differences of all the letters are less than 3", () => {
expect(checkAlmostEquivalent("abcaccc", "abaaacc")).toBeTruthy();
});

test("Return true if there is a letter which does not exist in either word1 or word2 and frequency differences of all the letters are less than 3", () => {
expect(checkAlmostEquivalent("cccddabba", "babababab")).toBeTruthy();
});

test("Return false if there is a letter which exists in both word1 and word2 or either of them has more than 3 frequency differences", () => {
expect(checkAlmostEquivalent("aaaa", "bccb")).toBeFalsy();
});