MediumNo. 0443

String Compression — LeetCode 443 Python Solution

Topics
Two Pointers, String
On a study list
LeetCode 75
Reading time
3 min

The 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 to s.

Example

Input
chars = ["a","a","b","b","c","c","c"]
Output
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation
The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

Python solution

PythonSolution
class Solution:
    def compress(self, chars: List[str]) -> int:
        i, k, n = 0, 0, len(chars)
        while i < n:
            j = i + 1
            while j < n and chars[j] == chars[i]:
                j += 1
            chars[k] = chars[i]
            k += 1
            if j - i > 1:
                cnt = str(j - i)
                for c in cnt:
                    chars[k] = c
                    k += 1
            i = j
        return k

Complexity

Time
O(n) (after optional sort O(n log n))
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 443. String Compression is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 443. String Compression?

LeetCode 443. String Compression is rated Medium on LeetCode.

What is the time complexity of LeetCode 443. String Compression?

The Python solution on this page runs in O(n) (after optional sort O(n log n)).

What is the space complexity of LeetCode 443. String Compression?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 443. String Compression cover?

LeetCode 443. String Compression is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.