What does it solve?
Given a character array chars, compress it in-place using run-length encoding. Each group of consecutive identical characters is replaced by the character followed by its count (omit count if 1). Return the new length.
Example: ["a","a","b","b","c","c","c"] → ["a","2","b","2","c","3"], return 6. Counts ≥ 10 are split digit by digit.
Two-pointer approach
// read = scans groups, write = places result
read = 0, write = 0
while read < n:
ch = chars[read]
count = 0
while chars[read] == ch: read++, count++
chars[write++] = ch
if count > 1:
for digit in str(count): chars[write++] = digit
read = 0, write = 0
while read < n:
ch = chars[read]
count = 0
while chars[read] == ch: read++, count++
chars[write++] = ch
if count > 1:
for digit in str(count): chars[write++] = digit
💡 Key insight: The write pointer never overtakes the read pointer — compression always produces ≤ as many characters as it reads. This guarantees in-place modification is safe. Think of it as two pointers on the same array: read scans ahead counting a group, write stamps the compressed result behind it.
Complexity
Time
O(n)
Each character is read exactly once by the read pointer.
Space
O(1)
Only two integer pointers — no extra arrays. Compression is in-place.
Examples & edge cases
Live animation — Read & Write Pointers
Read ptr (active)
Read ptr (counting group)
Write ptr (writing char)
Write ptr (writing digit)
Written (compressed)
📖 Input array — read pointer scans →
✏️ Output (in-place) — write pointer places result →
Current char
—
Group count
—
Group range
—
Writes
—
Output so far
nothing written yet
Step — of —
Read ptr
—
position
Write ptr
—
position
Output length
—
chars written
Groups done
0
compressed
Select an example and press Play to begin.
✓ Compressed!
Speed
Medium
Step-by-step table
| Step | Action | Read ptr | Write ptr | Char / digit | Group | Output so far |
|---|
C++ implementation
string_compression.cpp
#include <bits/stdc++.h> using namespace std; int compress(vector<char>& chars) { int read = 0, write = 0; int n = chars.size(); while (read < n) { char ch = chars[read]; int count = 0; // Count the full group of identical chars while (read < n && chars[read] == ch) { read++; count++; } // Write the character chars[write++] = ch; // Write count digits only if count > 1 if (count > 1) { string s = to_string(count); for (char d : s) chars[write++] = d; } } return write; } int main() { vector<char> chars = {'a','a','b','b','c','c','c'}; int len = compress(chars); cout << "New length: " << len << "\n"; // 6 // chars = ['a','2','b','2','c','3',...] return 0; }
My Notes