Search code examples
javascriptstringdata-structureslogic

need some easy solutions with short code in string compression in js


Here I have created a program for string compression, so for input chars = ["a","a","b","b","c","c","c"] we are getting output like 6 characters ["a","2","b","2","c","3"]. So I have created a program using the array approach, which is very lengthy and complex too. Is there any solution using the two-pointer or recursion approach to solve that program with very little code and efficiency? Can you please provide that with very short code? The code is given below.

var compress = function(chars) {
 if (!chars.length) {
    return 0;
  }
   let j = 0;                 
  let cur = chars[0];        
  let counter = 0;         
   for (let i = 0; i <= chars.length; i++) {
  
    if (chars[i] === cur) {
      counter++;              
    } else {
      // Otherwise, add the current character and count to the compressed array
      chars[j] = cur;        
      if (counter > 1) {
        const s = counter.toString();
        for (let k = 0; k < s.length; k++) {
          chars[++j] = s[k];  
        }
      }
      j++;                  
      cur = chars[i];      
      counter = 1;           
    }
   }
   return j
};
console.log(compress ('aaaabbc'))//a4b2c

Solution

  • Here is the solution using two pointers. Key concept here is: DO NOT PASS TWINCE FOR EACH ELEMENT IN THE INPUT.

    Complexity:

    • time: O(n)
    • space: O(n)
    const compress = (str) => {
      const result = [];
      for (let i = 0; i < str.length; ) {
        let j = i;
        while (str[j] == str[i]) {
          j++;
        }
        result.push(`${str[i]}${j - i == 1 ? '' : j - i}`);
        i = j;
      }
      return result.join('');
    };