Repository navigation
Patterns
Arghun-dev edited this page Jul 23, 2021
·
12 revisions
this pattern uses objects or sets to collect values/frequencies of values.
this can often avoid the need for nested loops or O(N^2) operations with arrays and strings.
Example
write a function which accepts two arrays. the function should return true if every value in the array has it's corresponding value squared in the second array. the frequency of values must be the same.
same([1,2,3], [4,1,9]) // true
same([1,2,3], [4,1,6]) // falsefunction same(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
let frequencyCounter1 = {};
let frequencyCounter2 = {};
for (let val of arr1) {
frequncyCounter1[val] = (frequencyCounter1[val] || 0) + 1;
}
for (let val of arr2) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1;
}
for (let key in frequencyCounter1) {
if (!(key ** 2 in frequencyCounter2)) return false;
if (frequencyCounter2[key] ** 2 !== frequencyCounter1[key]) return false;
}
return true;
}Anagrams
Given two strings, write a function to determine if the second is an anagram of the first. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
validAnagram("car", "rat"); // false
validAnagram("anagram", "nagaram") // trueValidAnagram.js
function validAnagram(first, second) {
let frequencyCounter1 = {};
for (let val of first) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1;
}
for (let val of second) {
if (!frequencyCounter1[val]) {
return false
} else {
frequencyCounter1[val]--;
}
}
return true;
}