15% off all plans & roadmaps Use code
See plansString Compression
- LeetCode 443
- Medium
- Two Pointers
- In-place Array Modification
Updated
TL;DR: Compress each run of repeated characters into the character plus its count, and write the result into the same array. Two pointers do this in one pass, because the compressed output is never longer than the run it replaces.
Problem
Given an array of characters chars, compress it with the algorithm below.
Start with an empty string s. Go through each group of consecutive repeating characters in chars.
- If a group has length 1, append its character to
s. - Otherwise, append its character, then the group's length as digits.
Store the compressed s in the input array chars. Do not return it separately. A group length of 10 or more takes several slots in chars.
After you modify the array, return the new length of the array. Your algorithm must use only constant extra space.
Example 1
Input: chars = ["a","a","b","b","c","c","c"] Output: 6, and the first 6 characters of the array are ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2
Input: chars = ["a"] Output: 1, and the first character of the array is ["a"] Explanation: The only group is "a". It stays uncompressed because its length is 1.
Example 3
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: 4, and the first 4 characters of the array are ["a","b","1","2"] Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
Constraints
1 <= chars.length <= 2000chars[i]is a lowercase English letter, uppercase English letter, digit, or symbol.
Constraints that matter
- n up to 2000 makes an O(n) pass easy, but the constant-space rule is the real limit. Any solution that builds a second array of the answer breaks it.
- Each slot in
charsholds one character. A count like 12 must be written as two slots, so the write step runs once per digit. - Each group of length k writes at most k slots, because a k of 2 or more needs only 1 + digits(k) slots. The write pointer can never pass the read pointer.
charscan contain digits, so you cannot parse the output back to find the groups. Track the groups with the read pointer while you scan.
Hints
Hint 1
Look at what each run turns into.
Hint 2
A beginner writes the obvious version first.
Solution
Intuition
Look at what each run turns into. A run of length 1 stays as one character. A longer run becomes one character plus the digits of its length. That is never more characters than the run had, so the answer always fits in the space the input already uses.
It is like a shopkeeper repacking a shelf of loose items in place. The reader is i, scanning ahead to count each run, and the writer is write, trailing behind to relabel slots already passed.
This points to the two pointers pattern for in-place array modification. One pointer reads ahead to find a whole run. A second pointer trails behind and writes the compressed output over the array. Because the writer never passes the reader, no unread character gets overwritten.
Check the constraints next. The problem asks for constant extra space and wants the answer stored in the input array. When the output is never longer than the input, that combination almost always means you can write in place. Sorting does not fit, because it would reorder the runs and change the output.
Worked example
Input: chars = ["a","b","c","d","e"] Output: 5 Explanation: Every group has length 1, so no group gets a count. The compressed string is "abcde", which has length 5. Because nothing repeats, the array stays the same and the function returns its length.
Approach 1: Brute force with a result list
A beginner writes the obvious version first. Scan the array run by run, build the compressed output in a new list, then copy that list back into chars. The answer is correct and runs in linear time.
The cost is memory. The new list can hold as many items as the input, so the extra space grows with n. The problem forbids that, so this version is the starting point and not the answer.
Steps
- Create an empty list
result, and setito 0. - While
iis less than n, savechars[i]incurrentand setcountto 0. - Advance
iwhilechars[i]equalscurrent, adding 1 tocountfor each match. - Append
currenttoresult. Ifcountis greater than 1, append each digit ofcounttoresult. - After the loop, copy
resultintocharsstarting at index 0, then return the length ofresult.
Dry run
Take chars = ["a","b","c","d","e"]. Each run has length 1, so the loop appends one value per run.
- Run 1:
currentis "a",countis 1.resultbecomes ["a"]. - Run 2:
currentis "b",countis 1.resultbecomes ["a","b"]. - Runs 3 to 5 add "c", "d", and "e" the same way.
The copy writes those five values back into chars, which leaves the array unchanged. The function returns 5.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of chars. The inner scan reads each index once, and i only moves forward, so the scans total n steps. Each append and each digit is constant work, and a count has at most 4 digits for n up to 2000. The result list holds at most the compressed length, which is at most n, so the extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def compress(self, chars: List[str]) -> int:
result = []
i = 0
n = len(chars)
while i < n:
current = chars[i]
count = 0
# Count the whole run before appending anything.
while i < n and chars[i] == current:
i += 1
count += 1
result.append(current)
if count > 1:
result.extend(str(count))
# Copy the compressed output back into chars.
for j in range(len(result)):
chars[j] = result[j]
return len(result)JavaTested in our runner
import java.util.*;
class Solution {
public int compress(String[] chars) {
List<String> result = new ArrayList<>();
int i = 0;
int n = chars.length;
while (i < n) {
String current = chars[i];
int count = 0;
// Count the whole run first. Use equals for String values.
while (i < n && chars[i].equals(current)) {
i++;
count++;
}
result.add(current);
if (count > 1) {
for (char d : Integer.toString(count).toCharArray()) {
result.add(String.valueOf(d));
}
}
}
for (int j = 0; j < result.size(); j++) {
chars[j] = result.get(j);
}
return result.size();
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int compress(vector<string>& chars) {
vector<string> result;
int i = 0;
int n = chars.size();
while (i < n) {
string current = chars[i];
int count = 0;
// Count the whole run before appending anything.
while (i < n && chars[i] == current) {
i++;
count++;
}
result.push_back(current);
if (count > 1) {
for (char d : to_string(count)) {
result.push_back(string(1, d));
}
}
}
for (int j = 0; j < static_cast<int>(result.size()); j++) {
chars[j] = result[j];
}
return static_cast<int>(result.size());
}
};JavaScriptTested in our runner
/**
* @param {string[]} chars
* @return {number}
*/
var compress = function(chars) {
const result = [];
let i = 0;
const n = chars.length;
while (i < n) {
const current = chars[i];
let count = 0;
// Count the whole run before appending anything.
while (i < n && chars[i] === current) {
i++;
count++;
}
result.push(current);
if (count > 1) {
for (const digit of String(count)) {
result.push(digit);
}
}
}
for (let j = 0; j < result.length; j++) {
chars[j] = result[j];
}
return result.length;
};GoTested in our runner
import "strconv"
func compress(chars []string) int {
result := []string{}
i := 0
n := len(chars)
for i < n {
current := chars[i]
count := 0
// Count the whole run before appending anything.
for i < n && chars[i] == current {
i++
count++
}
result = append(result, current)
if count > 1 {
for _, d := range strconv.Itoa(count) {
result = append(result, string(d))
}
}
}
copy(chars, result)
return len(result)
}C#Tested in our runner
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int compress(string[] chars) {
List<string> result = new List<string>();
int i = 0;
int n = chars.Length;
while (i < n) {
string current = chars[i];
int count = 0;
// Count the whole run before appending anything.
while (i < n && chars[i] == current) {
i++;
count++;
}
result.Add(current);
if (count > 1) {
foreach (char d in count.ToString()) {
result.Add(d.ToString());
}
}
}
for (int j = 0; j < result.Count; j++) {
chars[j] = result[j];
}
return result.Count;
}
}The In-place Array Modification infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
In-place Array Modification
Part of Two Pointers
Approach 2: One-pass two pointers, in placeOptimalIn-place Array Modification
What's slow: the brute force spends O(n) extra space on result. Most of that space is wasted, because the output can be written where the input already lives.
The insight that fixes it: write the compressed characters at write, a position that never catches up to i. Each run is fully read before anything is written over it. The output is never longer than the run it came from, so the writes stay behind the reads.
Why it is correct. The invariant is that write never exceeds i. Each run of length k becomes at most k characters, and the whole run is read before any of its slots are written.
Steps
- Set
writeandito 0, and let n be the length ofchars. - While
iis less than n, savechars[i]incurrentand setcountto 0. - Advance
iwhilechars[i]equalscurrent, adding 1 tocountfor each match. Finish the scan before writing. - Write
currentatchars[write], then advancewriteby 1. - If
countis greater than 1, write each digit ofcountatchars[write], advancingwriteafter each one. - When the loop ends, return
write. Slots afterwriteare leftovers, and the caller ignores them.
Dry run
The table traces the optimal approach on chars = ["a","b","c","d","e"].
| Run | i after scan | current | count | Writes at | write after | chars |
|---|---|---|---|---|---|---|
| 1 | 1 | a | 1 | index 0 | 1 | a, b, c, d, e |
| 2 | 2 | b | 1 | index 1 | 2 | a, b, c, d, e |
| 3 | 3 | c | 1 | index 2 | 3 | a, b, c, d, e |
| 4 | 4 | d | 1 | index 3 | 4 | a, b, c, d, e |
| 5 | 5 | e | 1 | index 4 | 5 | a, b, c, d, e |
Every run has length 1, so each write puts the same value back where it was. i reaches 5, which equals n, and the function returns write = 5.
Digits appear when a run repeats. For ["a","a","b","b","c","c","c"], the first run has count 2. After its scan, i is 2, and write writes a at index 0 and 2 at index 1. The write never touches data that is still unread.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of chars. The inner scan advances i once per index, and i never moves back, so all scans total n steps. A run of length k writes 1 + digits(k) slots, which is at most k, so the total writes are at most n. The variables write, i, count, and current are a fixed number, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def compress(self, chars: List[str]) -> int:
write = 0
i = 0
n = len(chars)
while i < n:
current = chars[i]
count = 0
# Scan the whole run before any write can touch it.
while i < n and chars[i] == current:
i += 1
count += 1
chars[write] = current
write += 1
if count > 1:
# Each slot holds one character, so write digits one by one.
for digit in str(count):
chars[write] = digit
write += 1
return writeJavaTested in our runner
import java.util.*;
class Solution {
public int compress(String[] chars) {
int write = 0;
int i = 0;
int n = chars.length;
while (i < n) {
String current = chars[i];
int count = 0;
// Scan the whole run before any write can touch it.
while (i < n && chars[i].equals(current)) {
i++;
count++;
}
chars[write++] = current;
if (count > 1) {
// Each slot holds one character, so write digits one by one.
for (char d : Integer.toString(count).toCharArray()) {
chars[write++] = String.valueOf(d);
}
}
}
return write;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int compress(vector<string>& chars) {
int write = 0;
int i = 0;
int n = chars.size();
while (i < n) {
string current = chars[i];
int count = 0;
// Scan the whole run before any write can touch it.
while (i < n && chars[i] == current) {
i++;
count++;
}
chars[write++] = current;
if (count > 1) {
// Each slot holds one character, so write digits one by one.
for (char d : to_string(count)) {
chars[write++] = string(1, d);
}
}
}
return write;
}
};JavaScriptTested in our runner
/**
* @param {string[]} chars
* @return {number}
*/
var compress = function(chars) {
let write = 0;
let i = 0;
const n = chars.length;
while (i < n) {
const current = chars[i];
let count = 0;
// Scan the whole run before any write can touch it.
while (i < n && chars[i] === current) {
i++;
count++;
}
chars[write++] = current;
if (count > 1) {
// Each slot holds one character, so write digits one by one.
for (const digit of String(count)) {
chars[write++] = digit;
}
}
}
return write;
};GoTested in our runner
import "strconv"
func compress(chars []string) int {
write := 0
i := 0
n := len(chars)
for i < n {
current := chars[i]
count := 0
// Scan the whole run before any write can touch it.
for i < n && chars[i] == current {
i++
count++
}
chars[write] = current
write++
if count > 1 {
// Each slot holds one character, so write digits one by one.
for _, d := range strconv.Itoa(count) {
chars[write] = string(d)
write++
}
}
}
return write
}C#Tested in our runner
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int compress(string[] chars) {
int write = 0;
int i = 0;
int n = chars.Length;
while (i < n) {
string current = chars[i];
int count = 0;
// Scan the whole run before any write can touch it.
while (i < n && chars[i] == current) {
i++;
count++;
}
chars[write++] = current;
if (count > 1) {
// Each slot holds one character, so write digits one by one.
foreach (char d in count.ToString()) {
chars[write++] = d.ToString();
}
}
}
return write;
}
}Common mistakes
chars[write] = str(count)writes the whole count into one slot. Each slot holds one character, so write each digit into its own slot.- Writing
currentbefore the inner scan finishes. The write can land on indices the scan still needs. Scan the whole run first, then write. - Checking
chars[i] == currentbeforei < n. This reads past the end of the array and throws an index error. Put the bounds check first in the condition. - Returning
noriinstead ofwrite. The judge reads only the firstwriteslots, so the other values give the wrong length. - Comparing Java strings with
==. It compares references, so equal values can compare unequal. Use.equalsfor each comparison. - Forgetting to reset
countto 0 at the start of each run. Counts carry over from the previous run, and the digits come out wrong.
Edge cases
["a"]returns 1, and the array is unchanged.- Ten
"a"values return 3, and the first three slots are "a", "1", "0". Nine"b"values return 2 as "b", "9". - Two thousand
"a"values return 5, and the first five slots are "a", "2", "0", "0", "0". ["a","b","a","b"]returns 4, and the array is unchanged because no run repeats.["1","1","1"]returns 2, and the first two slots are "1" and "3". Digit characters in the input are ordinary characters.
Follow-ups interviewers ask
- What if the answer must be returned as a new string instead of written into the array?
- Then you need an output buffer, and the extra space becomes O(n). The loop and the output stay the same. The constant-space trick only matters because the problem asks for the array itself to hold the answer.
- What if you sort
charsfirst, so equal characters sit together? - Sorting reorders the runs, so the output no longer describes the original groups. It would also cost O(n log n) for no gain. The two-pointer pass already sees each run in its original order.
- What if a run could be much longer, such as a billion equal characters?
- The algorithm still works, because it writes the digits of the count one at a time. In a language with 32-bit integers, a count above 2147483647 overflows, so use a 64-bit count in that case. A run of a billion writes 10 digit slots.
String Compression FAQ
What is the time complexity of String Compression?
It is O(n), where n is the length of chars. The read pointer moves forward through the array once, and each write does constant work. A count has only a few digits for this input, so the digit writes add a constant per run.
Why use two pointers for String Compression?
The output never grows past the run it replaces. That lets one pointer read ahead while another writes behind in the same array. Without the second pointer, you would need a separate buffer for the answer.
Can String Compression be solved in O(1) extra space?
Yes. The solution keeps write, i, count, and the current character. These are a fixed number of variables, so the extra space does not depend on n. A solution that builds a separate result list uses O(n) space.
Why does the returned length matter more than the array after it?
The judge reads only the first returned number of elements. Anything after write is leftover from the original input and is ignored. A wrong length fails the test even when the first characters are correct.
Why do I need to write count digits one at a time?
Each element of chars holds one character. The count 12 needs two slots, so writing str(count) as a single element is wrong in this format. Converting the count to a string and writing each digit handles every count.
Asked at
See which companies ask this — Pro
Related problems
- Sort Colors · same technique: In-place Array Modification
- Remove Duplicates from Sorted Array II · same technique: In-place Array Modification
- Move Pieces to Obtain a String · same technique: In-place Array Modification
- Separate Black and White Balls · same technique: In-place Array Modification
- Trapping Rain Water · same technique: In-place Array Modification
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers