#3800
Minimum Cost to Make Two Binary Strings Equal
MediumStringGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Count mismatches and resolve them using the cheapest operations. Pair opposite mismatches for efficient cost management.
⚙️
Algorithm
3 steps- 1Step 1: Count mismatches a (0 in s, 1 in t) and b (1 in s, 0 in t).
- 2Step 2: Calculate pairs p = min(a, b) and resolve with cost min(swapCost, 2 * flipCost).
- 3Step 3: Handle remaining mismatches with flipCost.
solution.py9 lines
1def minCost(s, t, flipCost, swapCost, crossCost):
2 a = b = 0
3 for i in range(len(s)):
4 if s[i] != t[i]:
5 if s[i] == '0': a += 1
6 else: b += 1
7 p = min(a, b)
8 cost = p * min(swapCost, 2 * flipCost) + (a - p + b - p) * flipCost
9 return costℹ
Complexity note: The complexity is linear since we only traverse the strings once to count mismatches.
- 1Identifying mismatches is crucial for minimizing costs.
- 2Pairing mismatches can lead to significant savings in operation costs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.