String Compression (In-Place)

Problem

Compress a character array in place using counts of repeated characters, and return the new length. Groups longer than 9 are split into multiple digit characters.

Input:  chars = ['a','a','b','b','c','c','c']
Output: 6, chars = ['a','2','b','2','c','3']

Python Solution

def compress(chars):
    write = 0
    read = 0
    n = len(chars)
    while read < n:
        char = chars[read]
        count = 0
        while read < n and chars[read] == char:
            read += 1
            count += 1
        chars[write] = char
        write += 1
        if count > 1:
            for digit in str(count):
                chars[write] = digit
                write += 1
    return write

C++ Solution

int compress(vector<char>& chars) {
    int write = 0, read = 0, n = chars.size();
    while (read < n) {
        char c = chars[read];
        int count = 0;
        while (read < n && chars[read] == c) { read++; count++; }
        chars[write++] = c;
        if (count > 1) {
            for (char digit : to_string(count)) chars[write++] = digit;
        }
    }
    return write;
}

Java Solution

class Solution {
    public int compress(char[] chars) {
        int write = 0, read = 0, n = chars.length;
        while (read < n) {
            char c = chars[read];
            int count = 0;
            while (read < n && chars[read] == c) { read++; count++; }
            chars[write++] = c;
            if (count > 1) {
                for (char digit : String.valueOf(count).toCharArray()) {
                    chars[write++] = digit;
                }
            }
        }
        return write;
    }
}

Complexity

Time: O(n) — the read pointer scans every character exactly once. Space: O(1) — compression happens in place using a separate write pointer, no second array allocated.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.