String Compression III - Problem
Given a string word, compress it using the following algorithm:
Begin with an empty string comp.
While word is not empty:
- Remove a maximum length prefix of
wordmade of a single charactercrepeating at most 9 times. - Append the length of the prefix followed by
ctocomp.
Return the string comp.
Input & Output
Example 1 — Basic Consecutive Characters
$
Input:
word = "abcde"
›
Output:
"1a1b1c1d1e"
💡 Note:
Each character appears exactly once, so each gets compressed to '1' + character
Example 2 — Repeated Characters with Limit
$
Input:
word = "aaaaaaaaaaaaaabb"
›
Output:
"9a5a2b"
💡 Note:
14 'a's become '9a' + '5a' (due to 9-character limit), 2 'b's become '2b'
Example 3 — Mixed Repetitions
$
Input:
word = "aabcccccccccaaa"
›
Output:
"2a1b9c1c3a"
💡 Note:
2 'a's → '2a', 1 'b' → '1b', 10 'c's → '9c1c', 3 'a's → '3a'
Constraints
- 1 ≤ word.length ≤ 2 × 105
- word consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with consecutive repeated characters
2
Process
Count consecutive chars in groups of max 9
3
Output
Compressed string with count+character pairs
Key Takeaway
🎯 Key Insight: Group consecutive identical characters and split groups larger than 9
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code