KatInterview

443. String Compression

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to compress an array of characters in-place. The compression rule involves grouping consecutive identical characters. If a group has length 1, it remains a single character. If its length is greater than 1, it's replaced by the character followed by its length. For example, "aaa" becomes "a3" and "b" remains "b". A key constraint is that the modification must happen on the input array itself (in-place) using only constant extra space. The function should return the new length of the compressed array.

Solution

String Compression in Python

class Solution:
    def compress(self, chars: list[str]) -> int:
        i = 0  # The pointer for writing the compressed characters.
        j = 0  # The pointer for reading the original characters.
        n = len(chars)

        while j < n:
            current_char = chars[j]
            group_start = j

            # Find the end of the group of consecutive repeating characters.
            while j < n and chars[j] == current_char:
                j += 1
            count = j - group_start

            # Write the character to the compressed part of the array.
            chars[i] = current_char
            i += 1

            # If the group count is greater than 1, write the count as characters.
            if count > 1:
                # To write the count in O(1) space, we can write digits in reverse
                # and then reverse that small segment of the array.
                start_of_digits = i
                temp = count
                while temp > 0:
                    chars[i] = str(temp % 10)
                    i += 1
                    temp //= 10
                
                # Reverse the written digits in-place to get the correct order.
                l, r = start_of_digits, i - 1
                while l < r:
                    chars[l], chars[r] = chars[r], chars[l]
                    l += 1
                    r -= 1

        # 'i' is the new length of the compressed array.
        return i

String Compression in Java

class Solution {
    public int compress(char[] chars) {
        int i = 0; // The pointer for writing the compressed characters.
        int j = 0; // The pointer for reading the original characters.
        int n = chars.length;

        while (j < n) {
            char currentChar = chars[j];
            int groupStart = j;

            // Find the end of the group of consecutive repeating characters.
            while (j < n && chars[j] == currentChar) {
                j++;
            }
            int count = j - groupStart;

            // Write the character to the compressed part of the array.
            chars[i++] = currentChar;

            // If the group count is greater than 1, write the count as characters.
            if (count > 1) {
                // To write the count in O(1) space, we can write digits in reverse
                // and then reverse that small segment of the array.
                int startOfDigits = i;
                int temp = count;
                while (temp > 0) {
                    chars[i++] = (char) ((temp % 10) + '0');
                    temp /= 10;
                }
                // Reverse the written digits to get them in the correct order.
                reverse(chars, startOfDigits, i - 1);
            }
        }

        // 'i' is the new length of the compressed array.
        return i;
    }

    private void reverse(char[] arr, int start, int end) {
        while (start < end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }
}

String Compression in C++

class Solution {
public:
    int compress(vector<char>& chars) {
        int i = 0; // The pointer for writing the compressed characters.
        int j = 0; // The pointer for reading the original characters.
        int n = chars.size();

        while (j < n) {
            char current_char = chars[j];
            int group_start = j;
            
            // Find the end of the group of consecutive repeating characters.
            while (j < n && chars[j] == current_char) {
                j++;
            }
            int count = j - group_start;

            // Write the character to the compressed part of the array.
            chars[i++] = current_char;

            // If the group count is greater than 1, write the count as characters.
            if (count > 1) {
                // To write the count in O(1) space, we can write digits in reverse
                // and then reverse that small segment of the array.
                int start_of_digits = i;
                int temp = count;
                while (temp > 0) {
                    chars[i++] = (temp % 10) + '0';
                    temp /= 10;
                }
                // Reverse the digits to get the correct order.
                std::reverse(chars.begin() + start_of_digits, chars.begin() + i);
            }
        }

        // 'i' is the new length of the compressed array.
        return i;
    }
};

String Compression in TypeScript

function compress(chars: string[]): number {
    let i = 0; // The pointer for writing the compressed characters.
    let j = 0; // The pointer for reading the original characters.
    const n = chars.length;

    const reverse = (arr: string[], start: number, end: number) => {
        while (start < end) {
            [arr[start], arr[end]] = [arr[end], arr[start]];
            start++;
            end--;
        }
    };

    while (j < n) {
        const currentChar = chars[j];
        let groupStart = j;

        // Find the end of the group of consecutive repeating characters.
        while (j < n && chars[j] === currentChar) {
            j++;
        }
        const count = j - groupStart;

        // Write the character to the compressed part of the array.
        chars[i++] = currentChar;

        // If the group count is greater than 1, write the count as characters.
        if (count > 1) {
            // To write the count in O(1) space, we can write digits in reverse
            // and then reverse that small segment of the array.
            const startOfDigits = i;
            let temp = count;
            while (temp > 0) {
                chars[i++] = (temp % 10).toString();
                temp = Math.floor(temp / 10);
            }
            // Reverse the written digits to get them in the correct order.
            reverse(chars, startOfDigits, i - 1);
        }
    }

    // 'i' is the new length of the compressed array.
    return i;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.