Compressing string in JavaScript

We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters.

The function should compress the string like this ?

'wwwaabbbb' -> 'w3a2b4'
'kkkkj' -> 'k4j'

And if the length of the compressed string is greater than or equal to the original string we should return the original string.

For example ?

'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab'

How It Works

The algorithm iterates through each character, counting consecutive occurrences. When a different character is found, it appends the character and its count to the result string.

Input: "wwwaabbbb" w w w a a b b b b Compression Process: Count consecutive: w(3) ? a(2) ? b(4) Output: "w3a2b4" w3 a2 b4 Original: 9 chars ? Compressed: 6 chars ?

Example

The code for this will be ?

const str1 = 'wwwaabbbb';
const str2 = 'kkkkj';
const str3 = 'aab';

const compressString = (str = '') => {
    let res = '';
    let count = 1;
    
    for(let i = 0; i < str.length; i++){
        let cur = str[i];
        let next = str[i + 1];
        
        if(cur === next){
            count++;
        } else {
            res += cur + String(count);
            count = 1;
        }
    }
    
    return res.length < str.length ? res : str;
};

console.log(compressString(str1));
console.log(compressString(str2));
console.log(compressString(str3));

Output

And the output in the console will be ?

w3a2b4
k4j1
aab

Key Points

  • The function only compresses consecutive repeated characters
  • Returns the original string if compression doesn't reduce length
  • Uses a counter to track character frequency
  • Resets the counter when a different character is encountered

Conclusion

String compression works by counting consecutive characters and replacing them with character-count pairs. This approach is most effective when strings contain long sequences of repeated characters.

Updated on: 2026-03-15T23:19:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements