VISUALGO//PROBLEMS
string compression · array / stringmedium
LeetCode #443
chars
a
a
b
b
c
c
c
output
·
ELEMENTS
chars
Python
def compress(chars: list[str]) -> int:
    write = 0
    read = 0

    while read < len(chars):
        char = chars[read]
        count = 0

        # Count consecutive same characters
        while read < len(chars) and chars[read] == char:
            read += 1
            count += 1

        # Write the character
        chars[write] = char
        write += 1

        # Write the count if > 1
        if count > 1:
            for digit in str(count):
                chars[write] = digit
                write += 1

    return write