Skip to content
Onsite

String Compression

MediumP2Coding

Compress the array of characters chars in place using these rules. Go through the array and split it into groups of consecutive equal characters. For each group, write the character; if the group has more than one character, also write its length as decimal digits, one digit per array element.

Use only O(1) extra space: the compressed form is written at the start of chars. Return the compressed array, that is, the first k elements of chars after compression, where k is the new length.

Example 1

Input
chars = ["a","a","b","b","c","c","c"]
Output
["a","2","b","2","c","3"]

Example 2

Input
chars = ["a"]
Output
["a"]

Example 3

Input
chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output
["a","b","1","2"]

Constraints

  • 1 <= chars.length <= 2000
  • Each element is a single lowercase letter, uppercase letter, digit or symbol.

Hints

Run checks the 3 visible tests, Submit all 11.