Anagram

by rishul matta

JavaScript

function populateAlphabetInMap(alphabet, map) {
    if (map[alphabet] === undefined) {
        map[alphabet] = 1;
    } else {
        var count = map[alphabet];
        count++;
        map[alphabet] = count;
    }
}

function calculateNosOfInsertionsToMakeThemSame(first, second) {
    var nosOfInsertions = 0;

    Object.keys(first).forEach(key => {
        var countInFirst = first[key];
        var countInSecond = second[key];

        if (countInSecond === countInFirst) {
            // means both words have same occurances of letter
            delete second[key];
        } else {
            if (countInSecond === undefined) {
                // means second word doesnt have this alphabet
                nosOfInsertions += countInFirst;
            } else {
                // both these words have these alphabets but counts are diff
                var difference = Math.abs(countInFirst - countInSecond);
                nosOfInsertions += difference;
                delete second[key];
            }
        }
    });

    Object.keys(second).forEach(key => {
        nosOfInsertions += second[key];
    });

    return nosOfInsertions;
}

function anagram(firstArr, secondArr) {
    var firstAlphabets = firstArr.split('');
    var secondAlphabets = secondArr.split('');

    var mapOfFirst = {};
    var mapOfSecond = {};

    firstAlphabets.forEach(alphabet => {
        populateAlphabetInMap(alphabet, mapOfFirst);
    });

    secondAlphabets.forEach(alphabet => {
        populateAlphabetInMap(alphabet, mapOfSecond);
    });

    return calculateNosOfInsertionsToMakeThemSame(mapOfFirst, mapOfSecond);
}