Leetcode 443: String Compression

grid47
grid47
Exploring patterns and algorithms
Sep 23, 2024 6 min read

A string shrinking as characters are compressed, with each compression step softly glowing.
Solution to LeetCode 443: String Compression Problem

Given an array of characters, compress it by replacing consecutive repeating characters with the character followed by the count of repetitions. If the character repeats only once, just include the character. The result should modify the input array and return the new length of the array.
Problem
Approach
Steps
Complexity
Input: The input is an array of characters where each character is a lowercase or uppercase letter, digit, or symbol.
Example: ["a","a","b","b","c","c","c"]
Constraints:
• 1 <= chars.length <= 2000
• chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
Output: The output should be the new length of the modified array, with the array itself being compressed in place.
Example: 6
Constraints:
• The modified array should be stored in the input array itself.
Goal: Efficiently compress the character array by grouping consecutive repeating characters and replacing them with the character followed by the count.
Steps:
• 1. Iterate over the characters in the input array.
• 2. For each group of consecutive repeating characters, append the character to the result.
• 3. If the group contains more than one character, append the length of the group as well.
• 4. Modify the input array in place to store the compressed version.
• 5. Return the new length of the array.
Goal: The input array should be compressed in place and no additional space should be used other than constant extra space.
Steps:
• 1 <= chars.length <= 2000
• The space complexity must be constant.
Assumptions:
• The input will always contain at least one character.
Input: ["a","a","b","b","c","c","c"]
Explanation: In this case, the consecutive characters 'a' and 'b' appear twice, while 'c' appears three times. The output compresses to ['a','2','b','2','c','3'].

Input: ["x"]
Explanation: The array has only one character, so no compression is necessary and the length remains 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus