DEV Community 👩‍💻👨‍💻


Posted on

String Compression

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

1) If the group's length is 1, append the character to s.
2) Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array. [means you have to modify the same array]

You must write an algorithm that uses only constant extra space.

Example 1:

Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

var compress = function (char) {
  let index = 0;
  let start = 0;
  let end = 0;
  let count = 0;

  while (char.length > end) {
    while (char[start] === char[end]) {
    char[index] = char[start];
    if (count > 1) {
      let toStr = count?.toString();
      for (let i = 0; i < toStr?.length; i++) {
        char[index] = toStr[i];
    count = 0;
    start = end;
  return index;
console.log(compress(["a", "a", "b", "b", "c", "c", "c"]));
  compress(["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"])

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs