- Group the array into repeated chunks, keeping track of the character and the count. This forms the encoded contents.
- Update the original array with the encodede contents. We maintain a
leftpointer to know which position to update the original array with the encoded contents and increment it according to the length of the encoded contents.
The encoded contents will definitely be shorter than the original contents, so we can overwrite the original without worries.
class Solution(object): def compress(self, chars): left = i = 0 while i < len(chars): char, length = chars[i], 1 while (i + 1) < len(chars) and char == chars[i + 1]: length, i = length + 1, i + 1 chars[left] = char if length > 1: len_str = str(length) chars[left + 1:left + 1 + len(len_str)] = len_str left += len(len_str) left, i = left + 1, i + 1 return left