String Compression
To solve this coding challenge, you need to compress a provided list of characters using a specific algorithm. The goal is to work with limited extra space while transforming the array in place.
# Explanation
The task involves iterating through the list of characters and finding consecutive repeating characters. When such groups are found:- If the group has a length of 1, you simply append the character to the result.
- If the group has a length greater than 1, you append the character followed by the group's length (split into individual character components).
Step-by-Step Explanation
- Initialize variables to keep track of the current character and group count.
- Traverse the list to identify groups of consecutive characters.
- For each group, write the character and its count back into the starting part of the array.
- When the groups are processed, the array will contain the compressed form at the beginning, and the new length of the compressed array will be returned.
- Initialization :
-
Start by checking if the input list
chars
0
-
Initialize
count
1
previousCharacter
writeIndex
0
- Iterate through the characters :
- Loop through the list starting from the second character.
-
For each character, check if it matches
previousCharacter
count
-
If it doesn't, write
previousCharacter
writeIndex
writeIndex
-
If
count
1
writeIndex
-
Update
previousCharacter
count
1
- Final Characters :
-
After the loop, handle the last group of characters by writing
previousCharacter
1
- Return the New Length :
-
The
writeIndex
Pseudocode Explanation
function compress(chars):
# Handling edge case where input list might be empty
if length of chars is 0:
return 0
# Initialize the initial character count and pointer to the initial character
count = 1
previousCharacter = chars[0]
writeIndex = 0 # This will point to the position in the array where we write characters
# Iterate over the characters starting from the second one
for i from 1 to length of chars - 1:
if chars[i] == previousCharacter:
# Current character is equal to previous, increment the count
count += 1
else:
# Current character is different
# Write the previous character and its count if greater than 1
chars[writeIndex] = previousCharacter
writeIndex += 1
if count > 1:
for digit in string representation of count:
chars[writeIndex] = digit
writeIndex += 1
# Update the previous character and reset count to 1
previousCharacter = chars[i]
count = 1
# Handle the last group of characters
chars[writeIndex] = previousCharacter
writeIndex += 1
if count > 1:
for digit in string representation of count:
chars[writeIndex] = digit
writeIndex += 1
# Return the new length of the modified array
return writeIndex