Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Compress the String
MEDIUM
25 mins
16 upvotes
Strings
Greedy
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Strings
-
-
Greedy
-
-
Other topics
Problem solved
Badge
Skill meter
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Compress the String

Contributed by
Aditya Agarwal
Medium
yellow-spark
0/80
Avg time to solve 25 mins
Success Rate 60 %
Share
16 upvotes

Problem Statement

Ninja has been given a program to do basic string compression. For a character that is consecutively repeated more than once, he needs to replace the consecutive duplicate occurrences with the count of repetitions.

Example:

If a string has 'x' repeated 5 times, replace this "xxxxx" with "x5".

The string is compressed only when the repeated character count is more than 1.

Note :

The consecutive count of every character in the input string is less than or equal to 9.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
2
aaabbddccc
ggttttffffrreee
Sample Output 1:
a3b2d2c3
g2t4f4r2e3
Explanation of Sample Input 1:
Test case 1:
For the first test case of sample output 1, our compressed string is “a3b2d2c3”. It represents that the string contains 3 consecutive ‘a’, 2 consecutive ‘b’, 2 consecutive ‘d’, and 3 consecutive ‘c’.
Sample Input 2:
1
xyzzz
Sample Output 2:
xyz3
Explanation of Sample Input 2:
Test case 1:
For the first test case of sample output 2, our compressed string is ‘xyz3’. As the occurrence of ‘x’ and ‘y’ is 1, hence we do not need to add the count of their repetitions. For the last character ‘z’, we have 3 repetitions.
Reset Code
Full screen
Auto
copy-code
Console