# Program to find string after deleting k consecutive duplicate characters in python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string s and another value k, we repeatedly delete the earliest k consecutive duplicate characters, and return the final string.

So, if the input is like s = "paaappmmmma" k = 3, then the output will be "ma", as when we delete three "a"s to get "pppmmmma". Then we delete three "p"s to get "mmmma". Then delete three of the four "m"s to get "ma".

To solve this, we will follow these steps:

• do the following steps infinitely, do
• count := 0
• chars := get the unique characters from s
• for each character c in chars, do
• if k consecutive c is in s, then
• delete k consecutive c from s
• count := count + 1
• if count is same as 0, then
• come out from the loop
• returns

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, s, k):
while True:
count = 0
chars = set(s)
for c in chars:
if c * k in s:
s = s.replace(c * k, "")
count += 1
if count == 0:
break
return s

ob = Solution()
s = "paaappmmmma"
k = 3
print(ob.solve(s, k))

## Input

"paaappmmmma", 3

## Output

ma