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 word made of a single character c repeating at most 9 times.
  • Append the length of the prefix followed by c to comp.

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
String Compression III OverviewInput: "aabcccccccccaaa"aabccccccccccaaa2a1b9c1c3aOutput: "2a1b9c1c3a"
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
Asked in
Google 25 Amazon 30 Microsoft 20 Facebook 15
12.5K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen