Created
April 28, 2025 09:50
-
-
Save kracekumar/626d0abb00bf5cfc8050d602deebb784 to your computer and use it in GitHub Desktop.
Given an array of characters chars, compress it such that consecutive duplicate characters are replaced with the character followed by the count of duplicates. If the count is 1, omit it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import groupby | |
def compress(items): | |
if not items: | |
return [] | |
result = [] | |
for item, group in groupby(items): | |
group_length = sum(1 for _ in group) | |
result.append(item) | |
if group_length > 1: | |
result.append(f"{group_length}") | |
return result | |
print(compress(["a", "a", "b", "b", "c", "c", "c"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment