Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created April 28, 2025 09:50
Show Gist options
  • Save kracekumar/626d0abb00bf5cfc8050d602deebb784 to your computer and use it in GitHub Desktop.
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.
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