Leetcode 443: String Compression
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.
Approach: The solution uses a greedy approach to iterate through the input array, compressing consecutive character groups in place without using extra space.
Observations:
• This problem requires modifying the array in place, so careful management of indices is necessary.
• We can use two pointers: one to track the current character and another to track the position where we will store the compressed result.
Steps:
• 1. Initialize two pointers, i for traversing the input array and j for filling the result in the same array.
• 2. Traverse the input array and count consecutive repetitions of the current character.
• 3. Append the character to the result, and if the repetition count is greater than 1, append the count as well.
• 4. Update the pointer j to reflect the new length of the array.
Empty Inputs:
• If the input array is empty, return 0.
Large Inputs:
• For large input arrays with many consecutive repeating characters, the solution must run efficiently in O(n) time.
Special Values:
• Consider cases where all characters are unique or all characters are the same.
Constraints:
• Ensure that no additional space is used beyond constant space for character count storage.
int compress(vector<char>& chars) {
if(chars.size() < 2) return chars.size();
int i = 0, j = 0;
while(i < chars.size()) {
chars[j] = chars[i];
int cnt = 0;
while(i < chars.size() && chars[i] == chars[j]) {
cnt++;
i++;
}
if(cnt == 1) {
j++;
} else {
string cntt = to_string(cnt);
for(auto ch: cntt) {
chars[++j] = ch;
}
j++;
}
}
return j;
}
1 : Function Declaration
int compress(vector<char>& chars) {
Defines the function to compress a vector of characters by replacing consecutive duplicates with the character and its count.
2 : Edge Case Check
if(chars.size() < 2) return chars.size();
Checks if the input vector has fewer than two characters. If so, no compression is needed, and the function returns the original size.
3 : Variable Initialization
int i = 0, j = 0;
Initializes two pointers, 'i' to traverse the input and 'j' to build the compressed version of the string.
4 : Main Loop
while(i < chars.size()) {
Begins a loop to traverse the input vector of characters.
5 : Character Assignment
chars[j] = chars[i];
Assigns the current character at 'i' to the position 'j' in the compressed vector.
6 : Counter Initialization
int cnt = 0;
Initializes a counter 'cnt' to track the number of consecutive occurrences of the current character.
7 : Count Consecutive Characters
while(i < chars.size() && chars[i] == chars[j]) {
Starts an inner loop to count consecutive characters that are the same as the current character at 'j'.
8 : Increment Count
cnt++;
Increments the counter 'cnt' for each consecutive occurrence of the current character.
9 : Move Pointer
i++;
Moves the pointer 'i' to the next character in the input vector.
10 : Handle Count
if(cnt == 1) {
Checks if there is only one occurrence of the character.
11 : Single Occurrence Handling
j++;
If the character occurs only once, simply moves the pointer 'j' to the next position.
12 : Handle Multiple Occurrences
} else {
If the character occurs more than once, the function will append the count to the vector.
13 : Count to String Conversion
string cntt = to_string(cnt);
Converts the count 'cnt' to a string so that its digits can be added to the vector.
14 : Appending Count Digits
for(auto ch: cntt) {
Iterates through the digits of the count and appends each digit to the compressed vector.
15 : Store Count Digit
chars[++j] = ch;
Stores each digit of the count in the appropriate position in the vector.
16 : Increment Pointer
j++;
Increments pointer 'j' after appending the count digits.
17 : Return Statement
return j;
Returns the new length of the compressed vector.
Best Case: O(n), where n is the length of the input array. This happens when there are no repetitions.
Average Case: O(n), because we still need to traverse the entire array.
Worst Case: O(n), where n is the length of the input array, even in the case of large repetitions.
Description: The solution traverses the array once, updating elements in place.
Best Case: O(1), since we do not use extra space except for the input array.
Worst Case: O(1), as we only use a few integer variables for indexing and counting.
Description: The space complexity is constant because we do not use any additional data structures.
LeetCode Solutions Library / DSA Sheets / Course Catalog |
---|
comments powered by Disqus