Problem Description
Given an array of characters, compress it in-place using a simple algorithm. For every group of consecutive repeating characters, append the character followed by the number of times it appears if the count is more than 1. The final compressed string must be stored in the same input array and the algorithm should use constant extra space.
Key Insights
- Use a two-pointer approach: one pointer for reading the original characters and one for writing the compressed result.
- Iterate through the array, counting consecutive duplicates.
- Write the character to the result followed by its count (if greater than 1), converting the count to its string representation.
- The algorithm works in-place with constant extra space aside from the counter and temporary variables.
Space and Time Complexity
Time Complexity: O(n), where n is the number of characters in the array. Space Complexity: O(1) (in-place compression with only a few extra variables).
Solution
The solution leverages a two-pointer technique:
- A "read" pointer traverses the array to identify groups of repeated characters.
- A "write" pointer updates the array with the compressed characters.
- For each group, after writing the character, if the group size is more than 1, the count is converted to a string and each digit is written sequentially.
- This in-place modification ensures constant extra space and the entire array is scanned once, resulting in O(n) time complexity.