LeetCode 443: String Compression Solution

Master LeetCode problem 443 (String Compression), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

443. String Compression

Problem Explanation

Explanation

To solve this problem, we iterate through the input array of characters and maintain two pointers - write and read. The read pointer moves through the array to count consecutive repeating characters, while the write pointer updates the array in-place with the compressed characters. We keep track of the current character and count the number of consecutive occurrences. When the characters change, we update the array with the compressed representation. Finally, we return the length of the compressed array.

  • Time complexity: O(n), where n is the length of the input array chars.
  • Space complexity: O(1) since we are using constant extra space.

Solution Code

class Solution {
    public int compress(char[] chars) {
        int write = 0;
        int start = 0;
        
        for (int read = 0; read < chars.length; read++) {
            if (read + 1 == chars.length || chars[read] != chars[read + 1]) {
                chars[write++] = chars[start];
                if (read > start) {
                    for (char c : String.valueOf(read - start + 1).toCharArray()) {
                        chars[write++] = c;
                    }
                }
                start = read + 1;
            }
        }
        
        return write;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 443 (String Compression)?

This page provides optimized solutions for LeetCode problem 443 (String Compression) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 443 (String Compression)?

The time complexity for LeetCode 443 (String Compression) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 443 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 443 in Java, C++, or Python.

Back to LeetCode Solutions