BackendML

String Compression

Medium2 min read
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 read = 0;
        
        while (read < chars.length) {
            char currentChar = chars[read];
            int count = 0;
            
            // Count all consecutive occurrences of the current character
            while (read < chars.length && chars[read] == currentChar) {
                count++;
                read++;
            }
            
            // Write the character itself
            chars[write++] = currentChar;
            
            // If the character appeared more than once, write the count digits
            if (count > 1) {
                for (char c : Integer.toString(count).toCharArray()) {
                    chars[write++] = c;
                }
            }
        }

        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.

Comments

No comments yet. Ask a question or share what helped.