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
gfgString Compression
Given 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:
- keep the character once,
- append its count as decimal digits only if the count is greater than 1.
Return the new length of the compressed array.
The compression must use only constant extra space beyond the output write positions.
Input Format
- A character array
charsof lengthn. - The array contains printable characters, and repeated characters may appear in consecutive runs.
Treat the array as mutable and modify it in place.
Output Format
- Return an integer: the length of the compressed array after rewriting it in place.
- The first returned-length elements of
charsshould contain the compressed result.
Constraints
- for interview-style practice.
- Use extra space.
- Encode counts in base 10.
- Counts may require multiple digits (for example,
12becomes'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'].
Show 1 more example
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
Unlock deeper context for this problem
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.