Anagrams

Benchmark created on


Setup

const arrayCompare = (a1, a2) => (a1.length === a2.length) && a1.every((v,i) => v === a2[i]);
const dataMock = [
    ['', '', ['']],
    ['I like cat and tac and act', 'act', [ 'cat', 'tac', 'act' ]],
    ['Silent lion lets Inlets stilets enlist Listens', 'listen', [ 'Silent', 'Inlets', 'enlist' ]],
    ['A Aa Aaa aaa aaaa aaaaa aba ', 'aaa', [ 'Aaa', 'aaa' ]],
    ['Aaa ab ba ba ba Ba Ab bab aabaa aba ', 'ab', [ 'ab', 'ba', 'Ba', 'Ab' ] ]

];

Test runner

Ready to run.

Testing in
TestOps/sec
Interview Solution
function solution(sentence, word) {
    const result = [];
    const targetWord = sortChars(word.toLowerCase());
    const words = sentence.toLowerCase().split(' ').filter(w => w.length === word.length);

    for (let i=0; i< words.length; i++) {
        const current = sortChars(words[i]);

        if (current === targetWord) {
            result.push(words[i]);
        }
    }

    return result;
}

function sortChars(word) {
    return word.split('').sort().join('');
}

dataMock.forEach((data, index) => {
    const result = solution(data[0], data[1]);
    console.assert(arrayCompare(result, data[2]), `Case #${index}: ${result} expected ${data[2]}`);
});
ready
Optimized Solution
function solution(sentence, word) {
    const words = sentence.split(' ');
    const targetWord = word.toLowerCase();
    const targetWordSize = new Set(targetWord).size;

    const anagrams = words.reduce((result, currentWord) => {
        if (currentWord.length !== word.length) {
            return result;
        }

        const wordSize = new Set(targetWord + currentWord.toLowerCase()).size;

        if (targetWordSize === wordSize) {
            result.add(currentWord);
        }

        return result;
    }, new Set);

    return [...anagrams];
}

dataMock.forEach((data, index) => {
    const result = solution(data[0], data[1]);
    console.assert(arrayCompare(result, data[2]), `Case #${index}: ${result} expected ${data[2]}`);
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.