Compress Problem - Javascript Challenge

DSL
1 min readDec 6, 2021
image credit by w3source.com

This challenge is to write a function, compress, that takes in an alphabetic string as an argument and generate a compressed version of it. See the following examples

'aaa' compresses to '5a'
'cc' compresses to '4c'
't' should remain as 't'

Please note that the compression only applied to characters that has more than one occurrence, e.g. aaa, if the character has only a single occurrence, e.g. t, it should remain unchanged. Here are a few test cases


'ccbb' compresses to '2c2b'
'ssssnnbb' compresses to '4s2n2b'
'bbbobbbbb' compresses to '3bo5b'

My first naive approach is to use hashMap through the reduce function as follow. However, it fails at the last test case, do you see why?

The reason it fails the last test is because hashMap property key is unique, so instead of getting 3bo5b, it made 8bo instead.

So the correct approach is to use index pointers and a while loop to solve it iteratively as the following.

Finally, I want to point out that the reason I used an array instead of using string directly for the concatenation is because string is immutable in Javascript. Therefore, to mutate string it requires O(n) complexity while pushing it into an array is O(1).

--

--

DSL

Sr software engineer. Love in Go, JavaScript, Python, and serverless AWS. Follow me for tech insights and experiences. follow me on twitter @terraformia