String Compression III - Problem

Given a string word, your task is to compress it using a specific run-length encoding algorithm with a twist - each run can contain at most 9 characters.

The compression algorithm works as follows:

  1. Start with an empty result string comp
  2. While the input string is not empty:
    • Find the longest prefix of consecutive identical characters (maximum 9)
    • Append the count followed by the character to comp
    • Remove this prefix from the input string

Example: If you have "aaabcccccccccc", you would get:

  • "aaa""3a"
  • "b""1b"
  • "ccccccccc""9c" (first 9 c's)
  • "c""1c" (remaining c)

Result: "3a1b9c1c"

Return the compressed string comp.

Input & Output

example_1.py — Basic Compression
$ Input: word = "aaabcccccccccc"
Output: "3a1b9c1c"
💡 Note: We have 3 consecutive 'a's, 1 'b', and 10 consecutive 'c's. Since we can only encode up to 9 characters at a time, the 10 'c's become '9c' + '1c'.
example_2.py — No Compression Needed
$ Input: word = "abcdef"
Output: "1a1b1c1d1e1f"
💡 Note: Each character appears only once, so each gets encoded as '1' followed by the character.
example_3.py — Maximum Run Length
$ Input: word = "aaaaaaaaaaaa"
Output: "9a3a"
💡 Note: We have 12 consecutive 'a's. The first 9 become '9a', and the remaining 3 become '3a'.

Constraints

  • 1 ≤ word.length ≤ 2 × 105
  • word consists of only lowercase English letters
  • Each compressed segment contains at most 9 consecutive identical characters

Visualization

Tap to expand
a a a a a a a a a a a b b cGroup 1: 9 a's→ "9a"Group 2: 2 a's→ "2a"Group 3: 2 b's→ "2b"Group 4: 1 c→ "1c"Final Result"9a2a2b1c"
Understanding the Visualization
1
Scan Characters
Move through string tracking current character and count
2
Count Matches
Increment count for identical consecutive characters
3
Handle Boundaries
When character changes or count reaches 9, output the group
4
Reset and Continue
Start new group with the different character
Key Takeaway
🎯 Key Insight: Track consecutive characters and their counts, outputting compressed groups when limits are reached or characters change
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.6K Views
Medium Frequency
~15 min Avg. Time
892 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