We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Apply Operations to Make Two Strings Equal

Difficulty: Medium


Problem Description

You are given two 0-indexed binary strings s1 and s2, both of length n, and a positive integer x. You can perform any of the following operations on the string s1 any number of times:

  • Choose two indices i and j, and flip both s1[i] and s1[j]. The cost of this operation is x.
  • Choose an index i such that i < n - 1 and flip both s1[i] and s1[i + 1]. The cost of this operation is 1.

Return the minimum cost needed to make the strings s1 and s2 equal, or return -1 if it is impossible.

Key Insights

  • The difference between s1 and s2 must be analyzed to determine the number of flips needed.
  • Flipping two bits at once (costing x) is generally more efficient when correcting larger mismatches compared to flipping adjacent bits (costing 1).
  • We can categorize the mismatches into pairs of flips needed and single flips, which will help optimize the cost.
  • The overall approach involves counting mismatches and calculating the minimum cost based on the operations allowed.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Solution

To solve this problem, we can use a greedy algorithm that first counts the number of mismatches between s1 and s2. We will:

  1. Iterate through the strings and identify mismatching pairs.
  2. For every two mismatches, we can choose to either flip both at a cost of x or flip them individually at a cost of 2 (if done separately).
  3. If there is an odd mismatch left, handle it with the adjacent flip operation.
  4. At the end, if there are any unmatched bits that cannot be flipped, return -1; otherwise, return the total cost calculated.

Code Solutions

def minCost(s1: str, s2: str, x: int) -> int:
    n = len(s1)
    cost = 0
    mismatch_count = 0

    for i in range(n):
        if s1[i] != s2[i]:
            mismatch_count += 1

    # Each pair of mismatches can be handled optimally
    pairs = mismatch_count // 2
    cost += pairs * min(x, 2)  # Cost for pairs
    if mismatch_count % 2 == 1:  # If there's an odd mismatch
        cost += 1  # One single adjacent flip

    return cost if mismatch_count % 2 == 0 or x < 2 else -1
← Back to All Questions