Before attempting this problem, you should be comfortable with:
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.
s to build the compressed result.i to traverse the array. For each position, find the extent of consecutive identical characters using a second pointer j.chars[i] to s.j - i is greater than 1, append the count as a string to s.i to j and repeat until the array is fully processed.s back to the chars array 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 iWe 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.
k = 0 as the write pointer and i = 0 as the read pointer.i < n, write chars[i] at position k and increment k.j starting at i + 1 to find all consecutive characters equal to chars[i].j - i exceeds 1, convert it to a string and write each digit to chars[k++].i to j and repeat.k as the new length of the compressed array.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.
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.
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.