String Compression III (LeetCode 3163): Solution and Explanation
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
- Start with an empty builder
compandi = 0. - Set
j = i, then advancejwhilej < n,j - i < 9andword[j] == word[i]. - Append the digit
j - iand the letterword[i]tocomp. - Set
i = jand repeat untili == n, then returncomp.
Step-by-step example
word = "aaaaaaaaaaaaaabb"
- i = 0: j runs over 9 a's and stops at the cap even though more a's follow. Append "9a", i = 9.
- i = 9: j covers the remaining 5 a's and stops at the first b. Append "5a", i = 14.
- i = 14: j covers both b's and stops at the end of the word. Append "2b", i = 16.
- 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)1class Solution {
2 public String compressedString(String word) {
3 StringBuilder comp = new StringBuilder();
4 int i = 0, n = word.length();
5 while (i < n) {
6 int j = i;
7 while (j < n && j - i < 9 && word.charAt(j) == word.charAt(i)) {
8 j++;
9 }
10 comp.append(j - i).append(word.charAt(i));
11 i = j;
12 }
13 return comp.toString();
14 }
15}1class Solution {
2public:
3 string compressedString(string word) {
4 string comp;
5 int i = 0, n = word.size();
6 while (i < n) {
7 int j = i;
8 while (j < n && j - i < 9 && word[j] == word[i]) {
9 j++;
10 }
11 comp += char('0' + (j - i));
12 comp += word[i];
13 i = j;
14 }
15 return comp;
16 }
17};Time and space complexity
O(n)
Every index is passed by j exactly once, and each append adds two characters.
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.