
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of flipping required to make all x before y in Python
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
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
- Related Articles
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to count number of swaps required to group all 1s together in Python
- Program to count minimum number of operations required to make numbers non coprime in Python?
- Program to count number of operations required to all cells into same color in Python
- Program to count number of operations required to convert all values into same in Python?
- Minimum number of flipping adjacent bits required to make given Binary Strings equal
- Number of operations required to make all array elements Equal in Python
- Python program to remove each y occurrence before x in List
- Python Program to Remove all digits before given Number
- Program to find minimum number of operations required to make one number to another in Python
- Program to count number of switches that will be on after flipping by n persons in python
- Program to count number of swaps required to change one list to another in Python?
- Program to count number of 5-star reviews required to reach threshold percentage in Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Program to count minimum number of operations to flip columns to make target in Python

Advertisements