Problem 443

Abstract / Summary

Given a string, write its compressed form by replacing consecutive repeated characters with the character followed by the count of repetitions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0443.py

class Solution:
    def compress(self, chars: List[str]) -> int:
        groups = []
        last = ""
        for c in chars:
            if c == last:
                groups[-1].append(c)
            else:
                groups.append([ c ])
                last = c

        pos = 0
        for g in groups:
            chars[pos] = g[0]
            pos += 1
            if len(g) > 1:
                for c in str(len(g)):
                    chars[pos] = c
                    pos += 1

        while len(chars) > pos:
            del chars[-1]

        return pos
24 lines | 595 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (1+ million submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a compress method that modifies an input list of characters in-place to produce a run-length encoded representation. The method returns the length of the compressed list. The algorithm proceeds in three logical phases: grouping consecutive identical characters, writing the compressed representation back into the original list, and removing any trailing elements that are no longer part of the result.

Grouping Phase

The first loop builds a list called groups where each element is a sub-list containing all occurrences of a consecutive character run. A variable last tracks the character seen in the previous iteration. When the current character matches last, the algorithm appends it to the most recent group; otherwise it starts a new group and updates last.

groups = []
last = ""
for c in chars:
    if c == last:
        groups[-1].append(c)
    else:
        groups.append([c])
        last = c

This approach isolates each maximal block of identical characters, which simplifies later processing because the length of each block is readily available as len(g).

Writing Compressed Output

After the groups are collected, a second loop iterates over them and writes the compressed form back into the original chars list. An index variable pos marks the next write position. For each group, the first character of the group is written, then, if the group length exceeds one, the decimal representation of the length is written digit by digit.

pos = 0
for g in groups:
    chars[pos] = g[0]
    pos += 1
    if len(g) > 1:
        for c in str(len(g)):
            chars[pos] = c
            pos += 1

By converting the length to a string, the code naturally handles multi-digit counts, ensuring that counts such as 12 are stored as two separate characters '1' and '2'.

Truncating Excess Elements

When the compressed representation is shorter than the original list, the tail of the list still contains leftover characters. The method removes these by repeatedly deleting the last element until the list length matches the final write position pos.

while len(chars) > pos:
    del chars[-1]

This loop guarantees that the returned length pos accurately reflects the size of the compressed data and that the list contains no extraneous characters beyond that point.

Edge Cases Handled

The algorithm gracefully handles an empty input list. In that scenario, the first loop never executes, groups remains empty, and the second loop does not run. The truncation loop also does not execute because len(chars) is already zero, and the method returns 0.

When the input consists of a single character, the grouping phase creates one group of length one. The writing phase writes that character and does not add a count because the length is not greater than one. No truncation is needed, and the method returns 1.

If a character appears in a run longer than nine, the conversion of the count to a string ensures that each digit is written separately. For example, a run of fifteen 'a' characters results in the sequence ['a', '1', '5']. This demonstrates correct handling of multi-digit counts without additional logic.

When the input contains alternating characters with no repeats, each character forms its own group of length one. The method writes each character directly and never adds a count, preserving the original order and length.

Performance Optimizations Observed

The code avoids creating intermediate strings for the entire compressed result; instead, it writes directly into the original list, which reduces memory overhead. The use of a single index pos to track the write location eliminates the need for additional data structures during the output phase.

Appending characters to groups using groups[-1].append(c) leverages list mutation, which is an O(1) operation for each append, keeping the grouping phase efficient. The conversion of the group length to a string occurs only when the length exceeds one, avoiding unnecessary string creation for single-character groups.

The final truncation loop deletes elements from the end of the list, which is an O(1) operation per deletion in Python's list implementation. By deleting only the surplus elements, the method ensures that the list size matches the compressed length without reallocating the entire list.

Overall, the implementation balances clarity with in-place modifications, achieving a compact representation while minimizing auxiliary storage and redundant processing steps.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long, messy line of colorful building blocks that are all mixed up. Some blocks are red, some are blue, and some are yellow, but they are all scattered around. This code is like a little robot helper that organizes those blocks into tidy piles.

First, the robot walks down the line of blocks. It looks at each block and checks if it matches the one right before it. If it sees a blue block and the previous one was blue too, it puts that blue block into a pile with its friends. If it sees a new color, it starts a brand-new pile. Now, instead of a messy line, there are neat little groups of blocks sitting on the floor.

Next, the robot starts putting the blocks back into a new, shorter line. For every group, it picks up one block so everyone knows what color the group is. If the group has more than one block, the robot counts how many there are and writes that number down on other blocks, placing them right next to the color block.

Finally, the robot looks at the very end of the line. If there are any old blocks left over that were not part of the new, organized list, the robot picks them up and puts them away in the toy box. Everything is now super tidy and takes up much less space than before.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.65 | σ = 1.11

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ Rust Python Go
LeetcodeHelp Java C++ Python
Progiez Java C++ Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
martianoff Scala
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
martianoff Scala
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Kotlin
zfang399 C++
35 links | 22 authors | 11 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality