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

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:


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:
      return s

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


"paaappmmmma", 3