443. String Compression
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 to s.
- 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 that 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.
Note: The characters in the array beyond the returned length do not matter and should be ignored.
Example 1:
Example 2:
Example 3:
- 1 <= chars.length <= 2000
- chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
Constraints:
Notes
Intuition
Compress in-place by using a read pointer to count consecutive characters and a write pointer to build the compressed result. The write pointer always stays behind or at the read pointer.
Implementation
Use three pointers: l (start of current group), r (scanner), and k (write position). Advance r while it matches chars[l] to count consecutive occurrences. Write the character at position k, then if the count (r - l) exceeds 1, write each digit of the count. Set l = r to start the next group. Return k as the new length.
Edge-cases
Single occurrences don't get a count appended (only the character is written). Multi-digit counts (e.g., 12) need each digit written separately.
- Time: O(n) — each character read and written once
- Space: O(1) — compression done in-place