String Compression

Problem Id: 443 Difficulty: Medium


Intuition

Solution


class Solution:
    def compress(self, chars: List[str]) -> int:
        start = 0
        end = 0
        index = 0
        while end < len(chars):
            while end < len(chars) and chars[end] == chars[start]:
                end += 1
            chars[index] = chars[start]
            index += 1

            if end - start > 1:
                for c in str(end - start):
                    chars[index] = c
                    index += 1
            start = end
        return index