Skip to content

Practice String Compression

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#443
LeetCode Problem

String Compression

Problem Statement

Compress each maximal consecutive run in chars in place. Write the run character once; if its length exceeds one, write the decimal digits of the length immediately after it. A run of length one has no count suffix. Store the compressed result at the start of chars and return its length. Characters beyond that length do not matter. Use only constant extra space, and do not return a separate compressed string.

Source: String Compression on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
chars = ["a","a","b","b","c","c","c"]
Output
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

# Example 2

Input
chars = ["a"]
Output
Return 1, and the first character of the input array should be: ["a"]

# Example 3

Input
chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Constraints

1 <= chars.length <= 2000
chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.

Related LeetCode Problems

Practice more problems similar to String Compression.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.