algoadvance

Leetcode 443. String Compression

Problem Statement

Given an array of characters chars, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a single character not a string of length 1.

The compressed string should be returned in the form of a new length of the array.

After you are done modifying the input array in-place, return the new length of the array.

The input array is a list of characters. Each character should be compressed as per the following rules:

Example

Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Input: chars = ["a"]
Output: Return 1, and the first 1 character of the input array should be: ["a"]

Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]

Clarifying Questions

  1. Q: Are the input arrays always non-empty? A: Yes, you can assume the input array has at least one character.

  2. Q: What should be done if the compressed length is longer than the original length? A: The problem guarantees that the compressed length will not be longer than the original length.

  3. Q: Should the returned length consider only the compressed array or the entire size of the array including trailing unused elements? A: The returned length should consider only the compressed array.

Strategy

Time Complexity

Code

public class Solution {
    public int compress(char[] chars) {
        int write = 0, read = 0;
        while (read < chars.length) {
            char currentChar = chars[read];
            int count = 0;

            // Count occurrence of the character
            while (read < chars.length && chars[read] == currentChar) {
                read++;
                count++;
            }

            // Write the character
            chars[write++] = currentChar;

            // Write the count if greater than 1
            if (count > 1) {
                for (char c : Integer.toString(count).toCharArray()) {
                    chars[write++] = c;
                }
            }
        }
        return write;
    }
}

Explanation

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI