Wednesday, January 27, 2021

String compression

Problem: 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.

We need to modify the input array itself. After you are done with modifications, return the new length of the array.

Example:

Input: chars = ["a","a","b","b","b","b","b"]
Output: Return 4 as the first 4 characters of input array will become: ["a","2","b","5"]
Explanation: The groups are "aa" and "bbbbb". This compresses to "a2b5".


Approach: Approach is straight forward. We are using two pointers here one is for read and second is for write. You can understand the approach by just looking at the implementation.


Implementation in C#:

        public int Compress(char[] chars)

    {
        int length = chars?.Length ?? 0;
        if (length <= 1)
        {
            return length;
        }
        int currCharCount = 1;
        int writeIndex = 1;
        for (int i = 1; i < length; ++i)
        {
            if (chars[i] == chars[i - 1])
            {
                ++currCharCount;
            }
            else
            {
                if (currCharCount > 1)
                {
                    this.AddCountToResult(chars, ref writeIndex, currCharCount);
                }
                currCharCount = 1;
                chars[writeIndex++] = chars[i];
            }
        }
        if (currCharCount > 1)
        {
            this.AddCountToResult(chars, ref writeIndex, currCharCount);
        }
        return writeIndex;
    }

    private void AddCountToResult(char[] chars, ref int writeIndex, int currCharCount)
    {
        string countStr = currCharCount.ToString();
        for (int j = 0; j < countStr.Length; ++j)
        {
            chars[writeIndex++] = countStr[j];
        }
    }


Complexity: O(n)

No comments:

Post a Comment