String Compression
Medium · Two Pointers · Explanation and code example
Two Pointers
How it works
We can compress the array in-place using two pointers: one for reading (i) and one for writing (k). Since the compressed form is never longer than the original (a character followed by its count takes at most as much space as the repeated characters), we can safely overwrite the array as we go. This eliminates the need for extra space.
Steps
- Initialize
k = 0as the write pointer andi = 0as the read pointer. - While
i < n, writechars[i]at positionkand incrementk. - Use pointer
jstarting ati + 1to find all consecutive characters equal tochars[i]. - If the count
j - iexceeds1, convert it to a string and write each digit tochars[k++]. - Move
itojand repeat. - Return
kas the new length of the compressed array.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Forgetting to Write Multi-Digit Counts Character by Character
When the count of consecutive characters exceeds 9 (e.g., 12), you must write each digit separately ('1' then '2') rather than treating it as a single value. Failing to split the count into individual digit characters will produce incorrect output.
Writing Count for Single Characters
The problem specifies that you should only write the count if it is greater than 1. A common mistake is writing "a1" instead of just "a" for a single occurrence. Always check if (count > 1) before appending the count to the result.
Overwriting Unprocessed Characters in In-Place Solutions
When compressing in place, the write pointer can overwrite characters that haven't been read yet if not handled carefully. Since the compressed form is never longer than the original, this won't happen as long as you process groups completely before moving the write pointer forward.
Python code example
from typing import List
class Solution:
def compress(self, chars: List[str]) -> int:
n = len(chars)
k = i = 0
while i < n:
chars[k] = chars[i]
k += 1
j = i + 1
while j < n and chars[i] == chars[j]:
j += 1
if j - i > 1:
for c in str(j - i):
chars[k] = c
k += 1
i = j
return k
C++ code example
class Solution {
public:
int compress(vector<char>& chars) {
int n = chars.size(), k = 0, i = 0;
while (i < n) {
chars[k++] = chars[i];
int j = i + 1;
while (j < n && chars[i] == chars[j]) {
j++;
}
if (j - i > 1) {
string cnt = to_string(j - i);
for (char c : cnt) {
chars[k++] = c;
}
}
i = j;
}
return k;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.