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

  1. Initialize an empty string s to build the compressed result.
  2. Use a pointer i to traverse the array. For each position, find the extent of consecutive identical characters using a second pointer j.
  3. Append the character chars[i] to s.
  4. If the count j - i is greater than 1, append the count as a string to s.
  5. Move i to j and repeat until the array is fully processed.
  6. Copy the compressed string 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 i

Time & Space Complexity

  • Time complexity: O(n)O(n) or O(n2)O(n ^ 2) depending on the language.
  • Space complexity: O(n)O(n)

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

  1. Initialize k = 0 as the write pointer and i = 0 as the read pointer.
  2. While i < n, write chars[i] at position k and increment k.
  3. Use pointer j starting at i + 1 to find all consecutive characters equal to chars[i].
  4. If the count j - i exceeds 1, convert it to a string and write each digit to chars[k++].
  5. Move i to j and repeat.
  6. Return k as the new length of the compressed array.
class Solution:
    def compress(self, chars: List[str]) -> int:
        n = len(chars)
        k = i = 0

        while i < n:
            chars[k] = chars[i]
            k += 1
            j = i + 1
            while j < n and chars[i] == chars[j]:
                j += 1

            if j - i > 1:
                for c in str(j - i):
                    chars[k] = c
                    k += 1
            i = j
        return k

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

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.