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
Difficulty
and has an acceptance rate of about 60% (1+ million submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 38: Count and Say
- problem 271: Encode and Decode Strings
- problem 1313: Decompress Run-Length Encoded List
- problem 3163: String Compression III
- problem 3167: Better Compression of String
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- 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