Developer Blog

Learn with me on the road to becoming a better engineer.

💻💡🧠⚙️

Frequency Counter

One of the first software patterns you should understand is the frequency counter.


A Frequency Counter pattern uses an object or a set to collect values and the frequencies of those values. This pattern can often avoid the need for nested loops or O(n2) operations with arrays / strings.

Implementation

Here is an implementation of a frequency counter in JavaScript to count the frequency of each number in a given array.

            
              let nums = [1,1,2,3,3,3,4,]
              // declare frequency counter object
              let frequencyCounter = {}

              // build frequency counter object
              for(let n of nums){
                frequencyCounter[n] = (frequencyCounter[n] || 0) + 1
              }
            
          

The frequency counter object built by our code is the following,

            
              frequencyCounter = 
              {
                '1' : 2,
                '2' : 1,
                '3' : 3,
                '4' : 1
              }
            
          

Use Cases

  • Whenever you have multiple pieces of data and you need to compare them
  • Any time you want to see if strings / arrays consist of the same individual pieces

Code Challenges

Listed below are some of the coding challenges that can be solved using the frequency counter pattern. Linked are solutions to each problem on my GitHub. I recommend trying to solve each problem without looking at the solution first. Good luck!

About

Firstly thanks for reading! My name is Michael and I am a software engineer. I write here about things that I have found helpful and interest me.

GitHub GitHub