FREQUENCY COUNTER PATTERN - rs-hash/Senior GitHub Wiki

1. FREQUENCY COUNTER

  • The Frequency Counter pattern is a technique used to count the occurrences of elements in a collection (like an array or string) and to solve problems involving comparison of frequencies in different collections. It helps in avoiding the need for nested loops and thus improves the time complexity of the solution.

  • Imagine you have a collection of items, and you want to count how many times each item appears. Instead of checking each item one by one and counting manually (which can be slow), you use an object (or a map) to keep track of the counts.

Here's how it works:

  • Create an object to store the counts of each item.
  • Loop through the collection, and for each item, increase its count in the object.
  • Use the object to quickly find out how many times each item appears.

EXAMPLES

1. Frequency counter

function frequencyCounter(str) {
    // Create an object to store the frequency of each character
    let frequency = {};

    // Loop through each character in the string
    for (let char of str) {
        // If the character is already in the object, increment its count
        // Otherwise, add the character to the object with a count of 1
        frequency[char] = (frequency[char] || 0) + 1;
    }

    // Return the frequency object
    return frequency;
}

// Example usage:
const str = "hello world";
const result = frequencyCounter(str);
console.log(result);

// Output

{
  h: 1,
  e: 1,
  l: 3,
  o: 2,
  ' ': 1,
  w: 1,
  r: 1,
  d: 1
}


2. Are Anagrams

function areAnagrams(str1, str2) {
    // If the strings have different lengths, they can't be anagrams
    if (str1.length !== str2.length) {
        return false;
    }

    // Create an object to count the frequency of characters in the first string
    let frequencyCounter1 = {};
    for (let char of str1) {
        frequencyCounter1[char] = (frequencyCounter1[char] || 0) + 1;
    }

    // Create an object to count the frequency of characters in the second string
    let frequencyCounter2 = {};
    for (let char of str2) {
        frequencyCounter2[char] = (frequencyCounter2[char] || 0) + 1;
    }

    // Compare the frequency objects
    for (let key in frequencyCounter1) {
        if (frequencyCounter1[key] !== frequencyCounter2[key]) {
            return false;
        }
    }

    return true;
}

// Example usage:
console.log(areAnagrams("cinema", "iceman")); // true
console.log(areAnagrams("hello", "billion")); // false


2. Simple Alternative for is strings Anagram


Simple solution
function areAnagrams(str1, str2) {
    return str1.split('').sort().join('') === str2.split('').sort().join('');
}

const inputStr1 = "listen";
const inputStr2 = "silent";
console.log(areAnagrams(inputStr1, inputStr2));

3. Anagram Groups

Description: Given an array of strings, group the anagrams together.

Input: ["eat", "tea", "tan", "ate", "nat", "bat"]

Output: ["eat","tea","ate"],["tan","nat"],["bat"](/rs-hash/Senior/wiki/"eat","tea","ate"],["tan","nat"],["bat")


function groupAnagrams(strs) {
    const groups = {};
    for (const word of strs) {
        const key = [...word].sort().join('');
        if (groups[key]) {
            groups[key].push(word);
        } else {
            groups[key] = [word];
        }
    }
    return Object.values(groups);
}

const inputArray = ["eat", "tea", "tan", "ate", "nat", "bat"];
console.log(groupAnagrams(inputArray));



4. Find Duplicates in Array

Description: Given an array of integers, find all the duplicates.

Input: [4,3,2,7,8,2,3,1]

Output: [2,3]


function findDuplicates(nums) {
    const duplicates = [];
    const count = {};
    for (const num of nums) {
        count[num] = (count[num] || 0) + 1;
        if (count[num] === 2) {
            duplicates.push(num);
        }
    }
    return duplicates;
}

const inputArray = [4, 3, 2, 7, 8, 2, 3, 1];
console.log(findDuplicates(inputArray));