Run-Length Compress a String In Place

medium string two pointers

Problem

Given a character array, compress consecutive runs of the same character to character + count, writing the result back into the same array. A run of length 1 omits the count. Return the new length.

Inputchars = ['a','a','a','b','b','c']
Output5 (chars becomes ['a','3','b','2','c', …])
Runs: a×3, b×2, c×1 → "a3b2c".

def compress(chars):
    write = read = 0
    while read < len(chars):
        run = read
        while run < len(chars) and chars[run] == chars[read]:
            run += 1
        chars[write] = chars[read]; write += 1
        n = run - read
        if n > 1:
            for d in str(n):
                chars[write] = d; write += 1
        read = run
    return write
function compress(chars) {
  let write = 0, read = 0;
  while (read < chars.length) {
    let run = read;
    while (run < chars.length && chars[run] === chars[read]) run++;
    chars[write++] = chars[read];
    const len = run - read;
    if (len > 1) for (const d of String(len)) chars[write++] = d;
    read = run;
  }
  return write;
}
class Solution {
    public int compress(char[] chars) {
        int write = 0, read = 0;
        while (read < chars.length) {
            int run = read;
            while (run < chars.length && chars[run] == chars[read]) run++;
            chars[write++] = chars[read];
            int len = run - read;
            if (len > 1) for (char d : String.valueOf(len).toCharArray()) chars[write++] = d;
            read = run;
        }
        return write;
    }
}
int compress(vector<char>& chars) {
    int write = 0, read = 0;
    while (read < (int)chars.size()) {
        int run = read;
        while (run < (int)chars.size() && chars[run] == chars[read]) run++;
        chars[write++] = chars[read];
        int len = run - read;
        if (len > 1) for (char d : to_string(len)) chars[write++] = d;
        read = run;
    }
    return write;
}
Time: O(n) Space: O(1) in place