DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 59

The task is to compress repeating letters with count number given a string.

The boilerplate code:

function compress(str) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If it's not a string, return ""

if(!str) return "";
Enter fullscreen mode Exit fullscreen mode

Start from the beginning of the string, and look at each character one by one. Keep a counter that tracks how many times the current character repeats consecutively.

let result = "";
let count = 1;
Enter fullscreen mode Exit fullscreen mode

If the next character is the same as the current one, increase the counter

for(let i=1; i <= str.length; i++) {
if(str[i] === str[i - 1] {
count++
}
}
Enter fullscreen mode Exit fullscreen mode

If the next character is different, the current group has ended. So add the character to the result, then add the count only if it is repeated more than once

 else {
      result += str[i - 1];
      if(count > 1) result += count
      count = 1;
    }
Enter fullscreen mode Exit fullscreen mode

The final code

function compress(str) {
  // your code here
  if(!str) return "";

  let result = "";
  let count = 1;

  for(let i=1; i <= str.length; i++) {
    if(str[i] === str[i-1]) {
      count++
    } else {
      result += str[i - 1];
      if(count > 1) result += count
      count = 1;
    }
  }
  return result;

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)