String Compression Algorithm: JavaScript Style

Rebecca Rosenberg
2 min readNov 1, 2020
https://javabypatel.blogspot.com/2016/07/string-compression-in-place-run-length-encoding-program.html

I took a code challenge as part of an interview process recently. One of the tasks was to write the so-called “string compression algorithm.” It was on HackerRank, so you could choose whichever style you pleased. I’ll be walking through how to complete this algorithm in JavaScript.

The question you’ll receive will basically say:

Compress a given string “aacccddd” to “a2c3d3”

The test I received added an additional rule. If the string was “abbccddd,”
compress it to “ab2c2d3.” In other words, if there was only one kind of letter consecutively, don’t give it a number.

So, we’re given a message and a function to begin with.

Somehow, within this function, we need to correlate a number with a letter. My first thought was to make a character map (i.e., an object with letters and their corresponding numbers). However, in this case, we don’t care about how many of each letter are actually in the string. We just care about if the same letter follows directly after.

Either way, we have a couple of initial steps:

  1. Split the string up into an array so we can properly iterate through it.
  2. Create a new string, which will hold the compressed version of the original one.
  3. Create a for loop.

Within the for loop, we need to keep track of two things for each iteration:

  1. The current count for the current consecutive letter(s), which will be set to one initially.
  2. The actual letter.

Next, we need to see if the currentLetter’s next neighbor is the same letter as itself. We’ll do this with a while loop, which will have two conditions: if i is less than messageArray’s length -1, AND if the current iteration is the same as it’s neighbor.

Here, while both conditions are met, we increase the count and the index position. This way, we go through all equivalent, consecutive occurrences of a letter, and only move onto the next new letter when the while loop’s conditions are no longer met.

Now all we need to do is add this letter and corresponding number to our compressedString. Remember, though, that if a letter had no consecutive neighbors, we don’t add a number to it. And, of course, don’t forget to return our compressedString!

That’s it!

--

--