Skip to main content

String Compression III - Solution & Explanation

MediumString14 min readAsked at: Amazon, Microsoft, Apple +4
Practice this problem

Problem Statement

Given a string word, compress it using the following algorithm:

  • Begin with an empty string comp. While word is not empty, use the following operation:
    • 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.

 

Example 1:

Input: word = "abcde"

Output: "1a1b1c1d1e"

Explanation:

Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.

For each prefix, append "1" followed by the character to comp.

Example 2:

Input: word = "aaaaaaaaaaaaaabb"

Output: "9a5a2b"

Explanation:

Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.

  • For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
  • For prefix "aaaaa", append "5" followed by "a" to comp.
  • For prefix "bb", append "2" followed by "b" to comp.

 

Constraints:

  • 1 <= word.length <= 2 * 105
  • word consists only of lowercase English letters.

Approach Overview

Problem Overview: Given a string word, build a compressed version where each group of consecutive identical characters is replaced with count + character. Each count can be at most 9, so longer runs must be split into multiple groups (e.g., 12 'a' → 9a3a).

Approach 1: Iterative Counting Approach (O(n) time, O(1) extra space)

Traverse the string from left to right and count consecutive occurrences of the same character. Maintain a running counter for the current character and append count + char whenever the count reaches 9 or the character changes. Reset the counter and continue scanning. This works because the compression rule only depends on contiguous characters, so a single pass with simple counting is sufficient. The algorithm processes each character once, giving O(n) time complexity with O(1) auxiliary space (excluding the output string).

Approach 2: Sliding Window Approach (O(n) time, O(1) extra space)

Use two pointers to form a window over runs of identical characters. The left pointer marks the start of a group, while the right pointer expands while the same character continues and the group size stays under 9. When the window reaches size 9 or encounters a different character, append the compressed segment and move the left pointer forward. This is a natural application of the sliding window pattern on a string, where the window represents the current run of identical characters. Every character enters and exits the window once, so the runtime remains O(n) with constant extra space.

Recommended for interviews: The iterative counting approach is typically expected. It demonstrates that you can process a string efficiently with a single pass and handle edge cases like runs longer than 9. The sliding window version shows familiarity with two-pointer patterns and is equally optimal, but the counting approach is usually the most straightforward explanation during interviews.

Approach 1: Iterative Counting Approach

This approach involves iterating through the string and counting consecutive characters. For each new character, append the count and character to the output string. If the count reaches 9, append and reset it.

This C solution uses an iterative approach where we count occurrences of each character up to a maximum of 9. We construct the result string manually.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as we store the result string separately.

Try this approach in the editor →

Approach 2: Sliding Window Approach

This approach is similar to the iterative approach but conceptualizes the counting as a sliding window over the input string. You increment the window until it changes character or hits the maximum prefix length.

This C solution uses two indices, start and end, to define a window over the string where characters are counted. Once the window reaches the maximum size or a different character is encountered, it appends to the result.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as it constructs the output string.

Try this approach in the editor →

Approach 3: Two Pointers

We can use two pointers to count the consecutive occurrences of each character. Suppose the current character c appears consecutively k times, then we divide k into several x, each x is at most 9, then we concatenate x and c, and append each x and c to the result.

Finally, return the result.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Approach 4: RegExp

Code

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Iterative Counting Approach

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as we store the result string separately.

Sliding Window Approach

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as it constructs the output string.

Two Pointers
RegExp

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative Counting ApproachO(n)O(1)Best general solution. Simple single pass and easy to implement in interviews.
Sliding Window ApproachO(n)O(1)Useful when practicing two‑pointer or sliding window patterns on strings.

Video Solution

String Compression III | Simple Simulation | Leetcode 3163 | codestorywithMIKcodestorywithMIK6,250 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is String Compression III easy or hard?
String Compression III is classified as a Medium problem on LeetCode. The logic is straightforward once you recognize it as a run-length encoding variant, but handling the "maximum count of 9 per group" constraint adds a small twist.
String Compression III Python/Java solution
In Python or Java, iterate through the string while counting consecutive characters. When the count hits 9 or the character changes, append the count and character to a result builder (like a list in Python or StringBuilder in Java). This produces the compressed output in linear time.
How to solve String Compression III in O(n)?
Traverse the string and maintain a counter for consecutive identical characters. When the count reaches 9 or the character changes, append the compressed segment (count followed by the character) and reset the counter. This single-pass strategy guarantees O(n) time complexity.
What is the best approach for String Compression III?
The iterative counting approach is the most common solution. You scan the string once, count consecutive characters, and append "count + character" to the result whenever the count reaches 9 or the character changes. This achieves O(n) time complexity with constant auxiliary space.
Is String Compression III asked at Google/Amazon/Meta?
String compression and run-length encoding variations appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary slightly, the core idea of grouping consecutive characters and limiting counts is a common string-processing pattern.
What data structure is used in String Compression III?
The problem mainly uses basic string traversal and counters. No advanced data structures are required—just variables to track the current character and its frequency, plus a string builder or buffer for the compressed result.
What is the time complexity of String Compression III?
The optimal solution runs in O(n) time because each character in the string is processed exactly once. Both the iterative counting and sliding window approaches maintain a single pass over the input. Space complexity is O(1) excluding the output string.

Ready to solve this problem?

Practice String Compression III with our built-in code editor and test cases.

Practice on FleetCode