The String Compression problem requires compressing consecutive groups of the same characters in an array while modifying the array in place.

Problem

Given an array of characters chars, compress it using the following rules. For each group of consecutive repeating characters, keep the character followed by its frequency if the frequency is greater than 1.

The compressed result must be stored in-place in the input array. Return the new length of the compressed array.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

chars = ["a","a","b","b","c","c","c"]

Output

["a","2","b","2","c","3"]
The returned length is:
6

Solution

This solution uses a Two Pointer approach. One pointer identifies the beginning of each group of consecutive characters, while another pointer scans the array to find the end of that group.

For each group, we write the character to the current position and, if the group contains more than one character, write its count as well. A separate pointer keeps track of the position where the compressed result should be written.

Because the result is written directly into the input array, no additional array is required.
class Solution {
    public int compress(char[] chars) {
        int write = 0;
        int i = 0;

        while (i < chars.length) {
            char current = chars[i];
            int j = i;

            while (j < chars.length && chars[j] == current) {
                j++;
            }

            chars[write++] = current;
            int count = j - i;

            // Handle multi-digit frequencies (e.g., 12 -> '1', '2')
            if (count > 1) {
                String countStr = String.valueOf(count);
                for (char c : countStr.toCharArray()) {
                    chars[write++] = c;
                }
            }
            i = j;
        }
        return write;
    }
}

Complexity

Each character is processed while scanning the groups, and the compressed characters are written back into the array. Therefore, the time complexity is O(n).

The compression is performed directly in the input array, so the algorithm uses O(1) extra space, excluding the temporary representation of the count.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion