Problem
Given a string word, compress it using the following algorithm:
- Begin with an empty string 
comp. Whilewordis not empty, use the following operation:- Remove a maximum length prefix of 
wordmade of a single charactercrepeating at most 9 times. - Append the length of the prefix followed by 
ctocomp. 
 - Remove a maximum length prefix of 
 
Return the string comp.
Examples
Example 1:
 |  | 
Example 2:
 |  | 
Solution
Method 1 - Count the continuous chars
- Initialisation:
- Initialise an empty string 
compto store the compressed result. - Initialise 
ito traverse theword. 
 - Initialise an empty string 
 - Loop through the word:
- While 
iis less than the length ofword:- Determine the current character 
cwhich isword[i]. - Count the length of the prefix of 
crepeating, but limit the count to a maximum of 9. - Append the count followed by 
cto thecompstring. - Increment 
iby the count to move to the next segment of the string. 
 - Determine the current character 
 
 - While 
 - Return the compressed string 
comp. 
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
 |  | 
 |  | 
Complexity
- ⏰ Time complexity: 
O(n), wherenis the length of theword. We traverse thewordonce. - 🧺 Space complexity: 
O(n). In the worst case scenario thecompstring can be of length2nsince each character can result in a numeric value and the character itself being appended.