Skip to main content

Frequency Counter Technique

Frequency Counter Technique

The Frequency Counter technique is a common approach for solving problems that involve counting occurrences of elements in an array or string. This technique can be implemented using objects or arrays to efficiently count and compare frequencies.

Overview

The Frequency Counter technique helps in problems where you need to:

  • Count the frequency of each element in a collection.
  • Compare the frequencies of elements.
  • Check for specific patterns or conditions based on element counts.

Implementation with Objects

Using an object to count frequencies is straightforward and effective for problems involving non-ASCII characters or when element values are not limited to a specific range.

Example: Counting Characters in a String

/**
* Count the frequency of each character in a string.
* @param {string} str - The input string.
* @return {object} - An object with characters as keys and their frequencies as values.
*/
const countCharacterFrequency = (str) => {
const frequencyCounter = {};

for (const char of str) {
frequencyCounter[char] = (frequencyCounter[char] ?? 0) + 1;
}

return frequencyCounter;
}

// Example usage:
const str = "hello world";
console.log(countCharacterFrequency(str));
// Output: { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }

Using ASCII numbers

/**
* Count the frequency of each letter in a string (lowercase letters only).
* @param {string} str - The input string.
* @return {number[]} - An array where the index corresponds to the letter (0 = 'a', 1 = 'b', ..., 25 = 'z').
*/
const countLetterFrequency = (str) => {
const frequencyCounter = Array(26).fill(0); // Array for 26 letters

for (const char of str) {
if (char >= 'a' && char <= 'z') {
frequencyCounter[char.charCodeAt(0) - 97]++; // 97 for lowercase, 65 for Uppercase
}
}

return frequencyCounter;
}

// Example usage:
const str = "hello";
console.log(countLetterFrequency(str));
// Output: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0]