Frequency Counters - rohit120582sharma/Documentation GitHub Wiki

Introduction

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 / strings.



Anagrams

Given two strings, write a function to determine if the second string is an anagram of the first.

An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

It's time compexity is 0(N).

function validAnagram(str1, str2){
    // Corner cases
    if(str1.length !== str2.length){
        return false;
    }

    // Declare objects
    let frequencyCounter1 = {};
    let frequencyCounter2 = {};

    // Add key(element of string) and set frequencies of elements as a key-value
    for(var element of str1){
        frequencyCounter1[element] = (frequencyCounter1[element] || 0) + 1;
    }
    for(var element of str2){
        frequencyCounter2[element] = (frequencyCounter2[element] || 0) + 1;
    }

    // Loop over frequencyCounter1
    for(var key in frequencyCounter1){
        if(!(key in frequencyCounter2)){
            return false;
        }
        if(frequencyCounter2[key] !== frequencyCounter1[key]){
            return false;
        }
    }

    // Return true
    return true;
}

validAnagram('', '') // true
validAnagram('aaz', 'zza') // false
validAnagram('cinema', 'iceman') // true
validAnagram('anagram', 'nagaram') // true
validAnagram("rat","car") // false) // false
validAnagram('awesome', 'awesom') // false
validAnagram('qwerty', 'qeywrt') // true
validAnagram('texttwisttime', 'timetwisttext') // true
⚠️ **GitHub.com Fallback** ⚠️