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 INPUT Input String: word a b c d e 0 1 2 3 4 word = "abcde" Length: 5 All unique characters No repeating sequences ALGORITHM STEPS 1 Initialize comp = "", i = 0 2 Count Repeats Count same char (max 9) 3 Append to comp Add count + character 4 Repeat Until end of string Single Pass Process: 'a' --> count=1 --> "1a" 'b' --> count=1 --> "1a1b" 'c' --> count=1 --> "1a1b1c" 'd','e' --> "1a1b1c1d1e" FINAL RESULT Compressed String: comp 1 a 1 b 1 c 1 d 1 e Output: "1a1b1c1d1e" OK - Complete Original length: 5 Compressed length: 10 Time: O(n) Space: O(n) Key Insight: The algorithm processes each character exactly once in a single pass. For each position, it counts consecutive identical characters (up to 9 max), then appends the count followed by the character. When all chars are unique (like "abcde"), each gets count 1, resulting in pairs: "1a1b1c1d1e". TutorialsPoint - String Compression III | Optimized Single Pass Approach
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