skip to Main Content

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

3

Answers


  1. You can use a two-pointer approach to achieve the string compression with a more concise code. Here’s a shorter version of your program:

    var compress = function(chars) {
      let i = 0;
      let count = 1;
      
      for (let j = 1; j <= chars.length; j++) {
        if (j < chars.length && chars[j] === chars[j - 1]) {
          count++;
        } else {
          chars[i++] = chars[j - 1];
    
          if (count > 1) {
            for (let digit of count.toString()) {
              chars[i++] = digit;
            }
          }
    
          count = 1;
        }
      }
    
      return i;
    };
    
    console.log(compress(['a', 'a', 'b', 'b', 'c', 'c', 'c']));
    console.log(compress('aaaabbc')); 
    
    Login or Signup to reply.
  2. Slightly modified two-pointer approach to avoid counter increments.
    I have labeled the variables so you can follow the code easily.

    var compress = function(chars) {
        let result = '';
        let currChar = 0;
        while(currChar < chars?.length) {
            let nextChar = currChar+1;
            while ((nextChar < chars.length) && (chars[currChar] === chars[nextChar]))
                nextChar++;
            let repeatFactor = nextChar-currChar;
            result += chars[currChar] + (repeatFactor > 1 ? (''+repeatFactor).trim() : '');
            currChar=nextChar;
        }
        return result;
    }
    

    Hope you will find this useful.

    Login or Signup to reply.
  3. 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) => {
      let result = '';
      for (let i = 0; i < str.length; ) {
        let j = i;
        while (str[j] == str[i]) {
          j++;
        }
        result = `${result}${str[i]}${j - i == 1 ? '' : j - i}`;
        i = j;
      }
      return result;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search