Program to count number of flipping required to make all x before y in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string s with letters x and y. Now consider an operation in which we change a single x to y or vice versa. We have to find the minimum number of times we need to perform that operation to set all x's come before all y's.

So, if the input is like s = "yxyyyyxyxx", then the output will be 4.

To solve this, we will follow these steps −

  • y_left := 0

  • x_right := number of "x" in s, res := number of "x" in s

  • for each item in s, do

    • if item is same as "x", then

      • x_right := x_right − 1

    • otherwise,

      • y_left := y_left + 1

    • res := minimum of res and (y_left + x_right)

  • return res

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s):
      y_left = 0
      x_right = res = s.count("x")
      for item in s:
         if item == "x":
            x_right -= 1
            y_left += 1
         res = min(res, y_left + x_right)
      return res
ob = Solution()
s = "yxyyyyxyxx"




Published on 26-Dec-2020 10:34:55