diff --git a/2068.check-whether-two-strings-are-almost-equivalent.js b/2068.check-whether-two-strings-are-almost-equivalent.js new file mode 100644 index 00000000..1761f57f --- /dev/null +++ b/2068.check-whether-two-strings-are-almost-equivalent.js @@ -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; \ No newline at end of file diff --git a/checkAlmostEquivalent.test.js b/checkAlmostEquivalent.test.js new file mode 100644 index 00000000..b289f95e --- /dev/null +++ b/checkAlmostEquivalent.test.js @@ -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(); +}); \ No newline at end of file