Prerequisites
Before attempting this problem, you should be comfortable with:
- Two Pointers Technique - Used to traverse and write to the array simultaneously while tracking consecutive characters
- In-Place Array Modification - Understanding how to modify an array without using additional space proportional to input size
- String to Integer Conversion - Converting count values to individual digit characters for multi-digit numbers
1. Using Extra Space
Intuition
The idea is to traverse the array and group consecutive identical characters together. For each group, we write the character followed by its count (only if count > 1). We first build the compressed string in a separate buffer, then copy it back to the original array. This approach is straightforward but uses extra space proportional to the output size.
Algorithm
- Initialize an empty string
sto build the compressed result. - Use a pointer
ito traverse the array. For each position, find the extent of consecutive identical characters using a second pointerj. - Append the character
chars[i]tos. - If the count
j - iis greater than1, append the count as a string tos. - Move
itojand repeat until the array is fully processed. - Copy the compressed string
sback to thecharsarray and return its length.
class Solution:
def compress(self, chars: List[str]) -> int:
n = len(chars)
s = ""
i = 0
while i < n:
s += chars[i]
j = i + 1
while j < n and chars[i] == chars[j]:
j += 1
if j - i > 1:
s += str(j - i)
i = j
i = 0
while i < len(s):
chars[i] = s[i]
i += 1
return iTime & Space Complexity
- Time complexity: or depending on the language.
- Space complexity:
2. Two Pointers
Intuition
We can compress the array in-place using two pointers: one for reading (i) and one for writing (k). Since the compressed form is never longer than the original (a character followed by its count takes at most as much space as the repeated characters), we can safely overwrite the array as we go. This eliminates the need for extra space.
Algorithm
- Initialize
k = 0as the write pointer andi = 0as the read pointer. - While
i < n, writechars[i]at positionkand incrementk. - Use pointer
jstarting ati + 1to find all consecutive characters equal tochars[i]. - If the count
j - iexceeds1, convert it to a string and write each digit tochars[k++]. - Move
itojand repeat. - Return
kas the new length of the compressed array.
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Forgetting to Write Multi-Digit Counts Character by Character
When the count of consecutive characters exceeds 9 (e.g., 12), you must write each digit separately ('1' then '2') rather than treating it as a single value. Failing to split the count into individual digit characters will produce incorrect output.
Writing Count for Single Characters
The problem specifies that you should only write the count if it is greater than 1. A common mistake is writing "a1" instead of just "a" for a single occurrence. Always check if (count > 1) before appending the count to the result.
Overwriting Unprocessed Characters in In-Place Solutions
When compressing in place, the write pointer can overwrite characters that haven't been read yet if not handled carefully. Since the compressed form is never longer than the original, this won't happen as long as you process groups completely before moving the write pointer forward.