Medium
Quiz
#443 String Compression
APPROACH
Given a character array chars, compress it in-place using run-length encoding. For each group of consecutive identical characters, write the character to the output; if the group has more than 1 character, also write the count digit-by-digit. Only O(1) extra space may be used.
Return the total length of the compressed data at the front of chars. Characters beyond that position can be ignored.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: 6
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: 1
Explanation: The only group is "a", which remains uncompressed since it's a single character.
Example 3:
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: 4
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
1 of 4
1:00
What is the optimal approach for this problem?