Encoding string to reduce its size in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of characters, str, as the only argument. Our function should encode the input string and compare its size with the original string and return the string which is smaller in size.

The rule to encode a particular string is −

  • n[s], where the s inside the square brackets is being repeated exactly k times.

For instance, ddd can be encoded to 3[d] but 3[d] has a length of 4 whereas ddd is only 3 characters long so our function should eventually return ddd.

For example, if the input to the function is −

const str = 'aabcaabcd';

Then the output should be −

const output = '2[aabc]d';

Example

The code for this will be −

 Live Demo

const str = 'aabcaabcd';
function encode(s) {
   const { length } = s;
   const dp = Array(length).fill([]);
   dp.forEach((el, ind) => {
      dp[ind] = Array(length).fill(null);
   });
   for(let l = 1; l <= length; l++){
      for(let i = 0; i + l <= length; i++){
         let j = i + l - 1;
         dp[i][j] = s.substring(i, j + 1);
         for (let k = i; k < j ; k ++) {
            let acc = dp[i][k] + dp[k + 1][j];
            if (acc.length < dp[i][j].length) {
               dp[i][j] = acc;
            }
         }
         let sub = s.substring(i, j + 1);
         let double = sub + sub;
         let cut = double.indexOf(sub, 1);
         if (cut != -1 && cut < sub.length) {
            let acc = sub.length / cut + "[" + dp[i][i + cut - 1] +"]";
            if (acc.length < dp[i][j].length) {
               dp[i][j] = acc;
            }
         }
      }
   }
   let res = dp[0][dp.length - 1];
   return res;
}
console.log(encode(str));

Output

And the output in the console will be −

2[aabc]d

Updated on: 04-Mar-2021

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements