String Compression (LeetCode 443): Solution and Explanation
Rewrite a character array in place so that each group of repeated characters becomes the character followed by its count (count omitted when it is 1), and return the length of the compressed prefix.
Intuition
With extra memory the problem is easy: build the compressed string in a new buffer and copy it back. The challenge is the constant-space requirement, which means writing the output into the same array you are still reading.
That is safe because compression never grows a group. A group of k equal characters becomes 1 character when k = 1, and 1 + digits(k) characters otherwise. For k >= 2, 1 + digits(k) <= k, so every group's output fits inside the space the group itself occupied.
So two pointers are enough. read finds where the current group ends; write is where the next output character goes. Since output never outgrows input, write stays at or behind read, and nothing you overwrite is still needed.
Remember to write counts of 10 or more as several characters, one per digit. That is why the answer for twelve b's is "b12", three slots, not two.
Approach: Read and write pointers
- Set
write = 0andread = 0. - While
read < len(chars), savech = chars[read]andstart = read, then advancereadwhilechars[read] == ch. - Write
chatchars[write]and incrementwrite. - If
count = read - startis greater than 1, write each digit ofstr(count)and advancewriteafter each. - Return
write.
Step-by-step example
chars = ["a","a","b","b","c","c","c"]
- Group 'a' spans indices 0 to 1, count 2. Write 'a' at 0 and '2' at 1, so
write = 2. - Group 'b' spans indices 2 to 3, count 2. Write 'b' at 2 and '2' at 3, so
write = 4. - Group 'c' spans indices 4 to 6, count 3. Write 'c' at 4 and '3' at 5, so
write = 6. readreaches 7, the end. The prefix is ["a","2","b","2","c","3"], so return 6.
Code: Python, Java, C++
1class Solution:
2 def compress(self, chars: List[str]) -> int:
3 write = 0
4 read = 0
5 while read < len(chars):
6 ch = chars[read]
7 start = read
8 while read < len(chars) and chars[read] == ch:
9 read += 1
10 chars[write] = ch
11 write += 1
12 count = read - start
13 if count > 1:
14 for d in str(count):
15 chars[write] = d
16 write += 1
17 return write1class Solution {
2 public int compress(char[] chars) {
3 int write = 0, read = 0;
4 while (read < chars.length) {
5 char ch = chars[read];
6 int start = read;
7 while (read < chars.length && chars[read] == ch) {
8 read++;
9 }
10 chars[write++] = ch;
11 int count = read - start;
12 if (count > 1) {
13 for (char d : String.valueOf(count).toCharArray()) {
14 chars[write++] = d;
15 }
16 }
17 }
18 return write;
19 }
20}1class Solution {
2public:
3 int compress(vector<char>& chars) {
4 int write = 0, read = 0, n = chars.size();
5 while (read < n) {
6 char ch = chars[read];
7 int start = read;
8 while (read < n && chars[read] == ch) {
9 read++;
10 }
11 chars[write++] = ch;
12 int count = read - start;
13 if (count > 1) {
14 for (char d : to_string(count)) {
15 chars[write++] = d;
16 }
17 }
18 }
19 return write;
20 }
21};Time and space complexity
O(n)
read moves forward over each character exactly once, and the digits written are bounded by the characters read.
O(1)
Only the two pointers and a small count are kept; the digit string of a count is at most 4 characters for n <= 2000.
Other approaches
Build a new string, then copy back (time O(n), space O(n))
Append the compressed form to a string builder and copy it into the front of chars. Simple and correct, but uses O(n) extra space, which the problem rules out.
Anchor pointer (time O(n), space O(1))
Keep an anchor at the first index of the current group and loop read over every index; when read is the last index or chars[read + 1] differs, write the group. Same idea with one loop instead of two nested ones.
Common mistakes
- Writing a count of 12 as one character. Each digit takes its own slot: 'b', '1', '2'.
- Writing '1' for groups of length 1. Single characters are written without a count.
- Reading
chars[read]after it has already been overwritten. Save the group character in a variable before writing. - Forgetting the last group when the loop ends exactly at the end of the array, which happens in single-loop versions that only flush on a change.
Frequently asked questions
Why can't the write pointer overtake the read pointer?
A group of k characters produces 1 + digits(k) output characters when k > 1 and 1 when k = 1. Both are at most k, so after each group the output is no longer than the input consumed.
What does the judge on this page check?
It checks the characters you wrote. After your function returns, the judge prints chars[0:length] using the length you returned, and compares that prefix with the expected compressed characters. A wrong length or a wrong digit both fail.
How do you write the digits without converting to a string?
Extract digits with repeated mod 10 into a small buffer and write it in reverse, or compute the highest power of 10 not above the count and divide down. The Go solution here builds the digits that way.