Remove Consecutive Duplicates in Python

Suppose we have a string s, this string consisting of "R" and "L", we have to remove the minimum number of characters such that there's no consecutive "R" and no consecutive "L".

So, if the input is like "LLLRLRR", then the output will be "LRLR"

To solve this, we will follow these steps −

  • seen := first character of s
  • ans := first character of s
  • for each character i from index 1 to end of s, do
    • if i is not same as seen, then
      • ans := ans + i
      • seen := i
  • return ans

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s):
      seen = s[0]
      ans = s[0]
      for i in s[1:]:
         if i != seen:
            ans += i
            seen = i
      return ans
ob = Solution()