String Compression III (LeetCode 3163): Solution and Explanation

Medium
String

Encode the word as pieces of one digit and one letter, where each piece covers a run of the same letter that is at most 9 long. Scan with an index i, extend j while the letter repeats and the run is under 9, append str(j - i) + word[i], then jump i to j. "aaaaaaaaaaaaaabb" becomes "9a5a2b".

Intuition

The removal rule always works on the front of what is left, so it is the same as walking the word left to right with one index.

A run longer than 9 cannot fit in one digit, so it is cut at 9 and the leftover letters simply start the next piece.

Each piece is exactly two characters, which makes the output easy to build with a string builder.

Approach: Run scan with a cap of 9

  1. Start with an empty builder comp and i = 0.
  2. Set j = i, then advance j while j < n, j - i < 9 and word[j] == word[i].
  3. Append the digit j - i and the letter word[i] to comp.
  4. Set i = j and repeat until i == n, then return comp.

Step-by-step example

word = "aaaaaaaaaaaaaabb"
  1. i = 0: j runs over 9 a's and stops at the cap even though more a's follow. Append "9a", i = 9.
  2. i = 9: j covers the remaining 5 a's and stops at the first b. Append "5a", i = 14.
  3. i = 14: j covers both b's and stops at the end of the word. Append "2b", i = 16.
  4. i equals the length, so the answer is "9a5a2b".

Code: Python, Java, C++

1class Solution:
2    def compressedString(self, word: str) -> str:
3        comp = []
4        i, n = 0, len(word)
5        while i < n:
6            j = i
7            while j < n and j - i < 9 and word[j] == word[i]:
8                j += 1
9            comp.append(str(j - i) + word[i])
10            i = j
11        return "".join(comp)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every index is passed by j exactly once, and each append adds two characters.

Space

O(n)

The output can be up to twice the input length (all runs of 1). Extra working space is O(1).

Other approaches

Single loop with a counter (time O(n), space O(n))

Walk every index once, keep a run counter, and flush count + letter whenever the letter changes or the counter reaches 9. Same result without the inner loop.

Full run lengths, then split (time O(n), space O(n))

Measure each whole run of length L, then emit L // 9 copies of "9c" and one "(L % 9)c" if the remainder is positive. Fewer comparisons on long runs, a little more bookkeeping.

Common mistakes

  • Writing the full run length, so 14 a's become "14a" instead of "9a5a".
  • Emitting an empty "0a" piece when a run is an exact multiple of 9, as in the split-after-counting variant.
  • Building the answer with repeated string concatenation in a language where that copies the whole string each time, which can turn the scan quadratic on 200,000 letters.

Frequently asked questions

Why can the count always be one digit?

The cap of 9 guarantees it. Any longer run is broken into several pieces of at most 9.

How is this different from String Compression (443)?

Problem 443 compresses in place, writes the full run length with as many digits as needed, and omits the count for runs of 1. Here every piece always has a single digit, including 1.

Can the output be longer than the input?

Yes. A word with no repeated neighbors, like "abcde", doubles in length because every letter gets a count of 1.