Compress a character array in place by replacing each run of repeated characters with the character followed by its count when the count is greater than 1.
LeetCode 443
gfgGiven an array of characters, rewrite it in place so that consecutive repeated characters are replaced by the character followed by the number of repetitions.
For each group of the same character:
Return the new length of the compressed array.
The compression must use only constant extra space beyond the output write positions.
chars of length n.Treat the array as mutable and modify it in place.
chars should contain the compressed result.12 becomes '1', '2').Example 1
Input
chars = ['a','a','b','b','c','c','c']
Output
6
Explanation
The runs are aa, bb, and ccc, so the array becomes ['a','2','b','2','c','3'] and the new length is 6.
Example 2
Input
chars = ['a']
Output
1
Explanation
A single character stays as is, so the compressed array is ['a'].
Example 3
Input
chars = ['a','b','b','b','b','b','b','b','b','b','b','b']
Output
4
Explanation
The result is ['a','b','1','1'] because the run of b has length 11.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.