15% off all plans & roadmaps Use code

See plans

String Compression

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 <= 2000
  • chars[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 chars holds 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.
  • chars can contain digits, so you cannot parse the output back to find the groups. Track the groups with the read pointer while you scan.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create an empty list result, and set i to 0.
  2. While i is less than n, save chars[i] in current and set count to 0.
  3. Advance i while chars[i] equals current, adding 1 to count for each match.
  4. Append current to result. If count is greater than 1, append each digit of count to result.
  5. After the loop, copy result into chars starting at index 0, then return the length of result.

Dry run

Take chars = ["a","b","c","d","e"]. Each run has length 1, so the loop appends one value per run.

  • Run 1: current is "a", count is 1. result becomes ["a"].
  • Run 2: current is "b", count is 1. result becomes ["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

TimeO(n)
SpaceO(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)

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 infographic

Solution 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

  1. Set write and i to 0, and let n be the length of chars.
  2. While i is less than n, save chars[i] in current and set count to 0.
  3. Advance i while chars[i] equals current, adding 1 to count for each match. Finish the scan before writing.
  4. Write current at chars[write], then advance write by 1.
  5. If count is greater than 1, write each digit of count at chars[write], advancing write after each one.
  6. When the loop ends, return write. Slots after write are leftovers, and the caller ignores them.

Dry run

The table traces the optimal approach on chars = ["a","b","c","d","e"].

Runi after scancurrentcountWrites atwrite afterchars
11a1index 01a, b, c, d, e
22b1index 12a, b, c, d, e
33c1index 23a, b, c, d, e
44d1index 34a, b, c, d, e
55e1index 45a, 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

TimeO(n)
SpaceO(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 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 current before the inner scan finishes. The write can land on indices the scan still needs. Scan the whole run first, then write.
  • Checking chars[i] == current before i < n. This reads past the end of the array and throws an index error. Put the bounds check first in the condition.
  • Returning n or i instead of write. The judge reads only the first write slots, so the other values give the wrong length.
  • Comparing Java strings with ==. It compares references, so equal values can compare unequal. Use .equals for each comparison.
  • Forgetting to reset count to 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 chars first, 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

Practise it