AlgoInsight

DSA problem

String Compression

MediumTwo PointersPattern: Two Pointers (read/write)top600AmazonGoogleMicrosoftApple

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

The compressed string s should not be returned separately, but instead be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array. You must write an algorithm that uses only constant extra space.

Examples

Example 1
Input: chars = ["a","a","b","b","c","c","c"]
Output: 6, and chars = ["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 chars = ["a"]
Explanation: The only group is "a", which remains uncompressed since it is a single character.
Example 3
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: 4, and chars = ["a","b","1","2"]
Explanation: The groups are "a" and twelve "b"s. This compresses to "ab12"; the length 12 is split into "1" and "2".

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

two-pointersstringarray

Browse all DSA problems