SDE & MLE Prep

443. String Compression

Problem

Compress the character array chars in place: each run of a repeated character becomes the character followed by the run length when it is longer than 1 (lengths of 10 or more take several characters). Return the new length.

Example: ["a","a","b","b","c","c","c"] → 6, with chars starting ["a","2","b","2","c","3"]

Constraints: O(1) extra space.

Read pointer finds each run [i, j); write pointer writes the character and, if the run is longer than 1, the digits of its length. The write pointer never overtakes the read pointer, so it works in place.

Complexity: O(n) time, O(1) extra space.

class Solution:
    def compress(self, chars: List[str]) -> int:
        w = i = 0
        while i < len(chars):
            j = i
            while j < len(chars) and chars[j] == chars[i]:
                j += 1
            chars[w] = chars[i]
            w += 1
            if j - i > 1:
                for d in str(j - i):
                    chars[w] = d
                    w += 1
            i = j
        return w