During my ongoing journey to become a strong problem solver, I’m quickly learning about the many patterns that can help solve algorithms that may appear as tricky. Take this problem for example:

- Write a function that takes in two arrays
- Each a array has a set of integers
- Return true if each index of the second array
contains the squared values of the first array
- The frequency of the values must be the same
[1, 2, 4], [1, 4, 16] => true
[1, 3, 8], [1, 9] => false

So just by reading this, it’s clear that we definitely need to iterate through the arrays, implement some conditional statements, and return a boolean. Let’s take a brute force approach to this problem before cleaning it up:

const hasSquared = (array1, array2) => {
  if (array1.length !== array2.length) return false;

  for (let i = 0; i < array1.length; i++) {
      const correctIndex = array2.indexOf(array[i] ** 2);
      if (correctIndex == -1) return false;
      array2.splice(correctIndex, 1);
  }
  return true;
}

For this solution, we first check to see if the frequency/length of the arrays are equal. Next, we use **indexOf() **to locate the index of array1’s squared values within the second array. If the index isn’t found then we return false. If we do find an index containing squared values, we splice it from the array and continue looping. We then return **true **once we exit our loop, confirming that **array2 **has the same frequency as **array1 **along with the squared values.

#computer-science #frequency-counter #coding #javascript #algorithms

Optimized Solutions: Frequency Counters
1.15 GEEK