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 tos. - Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead, be stored in the input character array chars.
Note: Group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Input & Output
Example 1 — Basic Compression
$
Input:
chars = ["a","a","b","b","c","c","c"]
›
Output:
6
💡 Note:
Groups: 'a' appears 2 times, 'b' appears 2 times, 'c' appears 3 times. Compressed: ['a','2','b','2','c','3']. Length is 6.
Example 2 — Single Characters
$
Input:
chars = ["a"]
›
Output:
1
💡 Note:
Single character 'a' with count 1, so no count is appended. Result: ['a']. Length is 1.
Example 3 — Mixed Groups
$
Input:
chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
›
Output:
4
💡 Note:
'a' appears 1 time (no count), 'b' appears 12 times. Compressed: ['a','b','1','2']. Length is 4.
Constraints
- 1 ≤ chars.length ≤ 2000
- chars[i] is a lowercase English letter, uppercase English letter, or digit
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code