Optimal: read and write pointers
Time O(n) Space O(1)read starts a run at index start and advances while characters match. Write the run's character at write. If the run length is above 1, write each digit of the length. The compressed form of a run (1 char plus at most its digits) is never longer than the run, so write stays at or behind read.
chars = [a, a, b, b, c, c, c]Step 1/4First run: 'a' twice (indexes 0..1).
class Solution {
public int compress(char[] chars) {
int write = 0, read = 0;
while (read < chars.length) {
char c = chars[read];
int start = read;
while (read < chars.length && chars[read] == c) read++;
chars[write++] = c;
int len = read - start;
if (len > 1) {
for (char d : Integer.toString(len).toCharArray()) chars[write++] = d;
}
}
return write;
}
}Verdict: Single pass, in place.