Skip to content

Patterns

Arghun-dev edited this page Jul 23, 2021 · 12 revisions

Frequency Counters

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]) // false
function 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;
}

Clone this wiki locally