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

jpantunes

JP Antunes

Posted on May 25, 2020

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('');
}
💖 💪 🙅 🚩
jpantunes
JP Antunes

Posted on May 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related