DEV Community

Cover image for Compress the String! - HackerRank Solution Python
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

9

Compress the String! - HackerRank Solution Python

Compress the String! is a medium-level Python problem that requires string manipulation. In this post, we will provide a Python solution for Compress the String.

Problem Statement and Explanation

You are given a string S. If a character ‘c’ occurs consecutively X times in the string, replace these consecutive occurrences of the character ‘c’ with (X, c) in the string.

Input Format

  • String S in the user input.

Output Format

  • Modified string S'

Compress the String Python Solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools
def compress_the_string(string):
res = itertools.groupby(string)
for k, g in res:
print((len(list(g)), int(k)), end=' ')
if __name__ == '__main__':
string = input()
compress_the_string(string)

Explanation of Solution

The first line imports the itertools module, which provides functions for working with iterators.

The next function, compress_the_string(), takes a string as input and returns a compressed version of the string. The function first uses the itertools.groupby() function to group the characters in the string together based on their equality. For example, the string “AAABBBCCC” would be grouped into the following pairs:

[('A', ['A', 'A', 'A']), 
('B', ['B', 'B', 'B']), 
('C', ['C', 'C', 'C'])]

Enter fullscreen mode Exit fullscreen mode

The function then iterates over the groups, printing the length of each group followed by the character that the group represents. For example, the compressed version of the string “AAABBBCCC” would be “3A2B3C”.

Here is a step-by-step explanation of how the code works:

  • The import itertools statement imports the itertools module.
  • The def compress_the_string(string): takes a string as input and returns a compressed version of the string.
  • The res = itertools.groupby(string): statement uses the itertools.groupby() function to group the characters in the string based on their equality.
  • The for k, g in res variable: statement iterates over the groups of characters.
  • The print((len(list(g)), int(k)), end=' ') statement prints the length of the group followed by the character that the group represents.
  • The if __name__ == ‘__main__’: clause defines the main function.
  • The string = input() statement prompts the user to enter a string.
  • The compress_the_string (string) statement calls the compress_the_string () function with the string that the user entered as input.
  • The print() statement prints the compressed version of the string to the console.

Time Complexity of the Solution

The time complexity of the solution is O(n), where n is the length of the input string. This is because of the itertools.groupby() function takes O(n) time to group the characters in the string. The for loop then iterates over the groups, which takes O(n) time. The print() statement takes constant time, so the overall time complexity is O(n).

Space Complexity of the Solution

The space complexity of the solution is O(n), where n is the length of the input string. This is because of the itertools.groupby() function creates a list of groups, which takes O(n) space. The for loop then iterates over the groups, which takes O(n) space. The print() statement takes constant space, so the overall space complexity is O(n).

The problem statement is taken from Hackerrank, and the solutions are implemented by the CodePerfectPlus team

30 Days of Code SubReddit

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up