DEV Community

JP Antunes
JP Antunes

Posted on

3 1

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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay