# Program to count number of flipping required to make all x before y 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 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 −

## Example

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
else:
y_left += 1
res = min(res, y_left + x_right)
return res
ob = Solution()
s = "yxyyyyxyxx"
print(ob.solve(s))

## Input

"yxyyyyxyxx"

## Output

4
Updated on 26-Dec-2020 10:37:17