String Compression LeetCode Solution

Last updated on January 5th, 2025 at 01:10 am

Here, we see a String Compression LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

String

Companies

Bloomberg, Microsoft, Snapchat, Yelp

Level of Question

Medium

String Compression LeetCode Solution

String Compression LeetCode Solution

1. Problem Statement

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

  • If the group’s length is 1, append the character to s.
  • Otherwise, append the character followed by the group’s length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

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

You must write an algorithm that uses only constant extra space.

Example 1:
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″]
Explanation: The groups are “aa”, “bb”, and “ccc”. This compresses to “a2b2c3”.

Example 2:
Input: chars = [“a”]
Output: Return 1, and the first character of the input array should be: [“a”]
Explanation: The only group is “a”, which remains uncompressed since it’s a single character.

Example 3:
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″].
Explanation: The groups are “a” and “bbbbbbbbbbbb”. This compresses to “ab12”.

2. Coding Pattern Used in Solution

The coding pattern used in this code is “Two Pointers”. The code uses two pointers (i and j in JavaScript, or i and ans in other languages) to traverse and modify the input array in-place. The i pointer keeps track of the position where the compressed result is written, while the j pointer (or the inner loop) iterates through the array to count consecutive occurrences of characters.

3. Code Implementation in Different Languages

3.1 String Compression C++

class Solution {
public:
    int compress(vector<char>& chars) {
        int ans = 0;
        for (int i = 0; i < chars.size();) {
            const char letter = chars[i];
            int count = 0;
            while (i < chars.size() && chars[i] == letter) {
                ++count;
                ++i;
            }
            chars[ans++] = letter;
            if (count > 1) {
                for (const char c : to_string(count)) {
                    chars[ans++] = c;
                }
            }
        }
        return ans;
    }
};

3.2 String Compression Java

class Solution {
  public int compress(char[] chars) {
    int ans = 0;
    for (int i = 0; i < chars.length;) {
      final char letter = chars[i];
      int count = 0;
      while (i < chars.length && chars[i] == letter) {
        ++count;
        ++i;
      }
      chars[ans++] = letter;
      if (count > 1) {
        for (final char c : String.valueOf(count).toCharArray()) {
          chars[ans++] = c;
        }
      }
    }
    return ans;
  }
}

3.3 String Compression JavaScript

var compress = function(chars) {
    let i = 0;
    let j = 0;
    while (j < chars.length) {
        let count = 0;
        let curr = chars[j];
        while (j < chars.length && chars[j] === curr) {
            j++;
            count++;
        }
        chars[i++] = curr;
        if (count > 1) {
            for (let digit of count.toString()) {
                chars[i++] = digit;
            }
        }
    }
    return i;
};

3.4 String Compression Python

class Solution(object):
    def compress(self, chars):
        ans = 0
        i = 0
        while i < len(chars):
            letter = chars[i]
            count = 0
            while i < len(chars) and chars[i] == letter:
                count += 1
                i += 1
            chars[ans] = letter
            ans += 1
            if count > 1:
                for c in str(count):
                    chars[ans] = c
                    ans += 1
        return ans

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n + log k)O(1)
JavaO(n + log k)O(1)
JavaScriptO(n + log k)O(1)
PythonO(n + log k)O(1)

where, n is the size of chars and k is the count of consecutive characters.

  • The code modifies the input array in-place, so no additional space is used apart from a few variables.
  • The log k factor in time complexity comes from converting the count to a string, but this is negligible for most practical inputs.
  • The algorithm is efficient for compressing strings with repeated characters, as it avoids creating a new array and works directly on the input.
Scroll to Top