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

When we have a string containing only 'x' and 'y' characters, we want to find the minimum number of character flips needed to arrange all 'x' characters before all 'y' characters. This means we need to achieve a pattern like "xxx...yyy".

The key insight is that for any partition point in the string, we can calculate the cost by counting 'y' characters on the left (which need to become 'x') and 'x' characters on the right (which need to become 'y').

Algorithm

We iterate through each possible partition point and track:

  • y_left: Number of 'y' characters encountered so far

  • x_right: Number of 'x' characters remaining to the right

  • res: Minimum flips needed (initially set to total 'x' count)

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

# Test the solution
ob = Solution()
s = "yxyyyyxyxx"
print(f"Input: {s}")
print(f"Minimum flips needed: {ob.solve(s)}")
Input: yxyyyyxyxx
Minimum flips needed: 4

How It Works

For the string "yxyyyyxyxx":

  • Total 'x' characters: 4

  • We try each partition point and calculate cost as y_left + x_right

  • The algorithm finds the optimal partition where the total cost is minimized

  • At the optimal point, we need 4 flips to achieve the desired arrangement

Alternative Approach

Here's a simpler function-based implementation:

def min_flips_to_arrange(s):
    """
    Find minimum flips to arrange all x before all y
    """
    y_left = 0
    x_right = s.count('x')
    min_flips = x_right  # worst case: flip all x to y
    
    for char in s:
        if char == 'x':
            x_right -= 1
        else:
            y_left += 1
        min_flips = min(min_flips, y_left + x_right)
    
    return min_flips

# Test with multiple examples
test_cases = ["yxyyyyxyxx", "xxxyyyy", "yyyyxxx", "xyxyxy"]

for test in test_cases:
    result = min_flips_to_arrange(test)
    print(f"'{test}' ? {result} flips")
'yxyyyyxyxx' ? 4 flips
'xxxyyyy' ? 0 flips
'yyyyxxx' ? 3 flips
'xyxyxy' ? 2 flips

Conclusion

The algorithm efficiently finds the minimum flips by trying each partition point and calculating the cost as the sum of misplaced characters. The time complexity is O(n) and space complexity is O(1), making it an optimal solution.

Updated on: 2026-03-25T13:59:47+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements