DEV Community

JP Antunes
JP Antunes

Posted on

Compress a string such that 'AAABCCDDDD' becomes 'A3B1C2D4'

This seems to be a popular interview question that I stumbled upon in an Anki deck

const compress = str => {
        //build a character frequency map
    const freqM = [...str].reduce((acc, val) => { 
        acc[val] = acc[val] + 1 || 1; 
        return acc;
    }, {});
        //return str if length <= unique characters * 2 (ie, 'A' vs 'A1') 
    if (str.length <= Object.keys(freqM).length * 2) return str;
        //return the frequency map as a string otherwise 
    return  Object.entries(freqM).flat().join('');
}

Top comments (0)