#2896
Apply Operations to Make Two Strings Equal
MediumStringDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages dynamic programming to minimize the cost of operations by focusing on the differing indices. This approach efficiently calculates the minimum cost by considering the costs of flipping adjacent bits and pairs.
⚙️
Algorithm
3 steps- 1Step 1: Identify all indices where s1 and s2 differ and store them in a list.
- 2Step 2: Use dynamic programming to calculate the minimum cost to make the strings equal based on the differing indices.
- 3Step 3: For each differing index, decide whether to use the cost of flipping pairs or adjacent bits based on the minimum cost calculated so far.
solution.py11 lines
1def minCost(s1, s2, x):
2 n = len(s1)
3 diff = [i for i in range(n) if s1[i] != s2[i]]
4 m = len(diff)
5 dp = [float('inf')] * (m + 1)
6 dp[0] = 0
7 for i in range(m):
8 dp[i + 1] = min(dp[i + 1], dp[i] + 1) # flip adjacent
9 if i + 1 < m:
10 dp[i + 2] = min(dp[i + 2], dp[i] + x) # flip pair
11 return dp[m] if dp[m] != float('inf') else -1ℹ
Complexity note: This complexity is linear because we only traverse the differing indices and maintain a dynamic programming array proportional to the number of differences.
- 1Understanding the cost of operations is crucial to minimize the total cost.
- 2Dynamic programming can significantly reduce the complexity by breaking the problem into smaller subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.