Leetcode #2976: Minimum Cost to Convert String I
In this guide, we solve Leetcode #2976 Minimum Cost to Convert String I in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arrays original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Graph, Array, String, Shortest Path
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]
Output: 28
Explanation: To convert the string "abcd" to string "acbe":
- Change value at index 1 from 'b' to 'c' at a cost of 5.
- Change value at index 2 from 'c' to 'e' at a cost of 1.
- Change value at index 2 from 'e' to 'b' at a cost of 2.
- Change value at index 3 from 'd' to 'e' at a cost of 20.
The total cost incurred is 5 + 1 + 2 + 20 = 28.
It can be shown that this is the minimum possible cost.
Python Solution
class Solution:
def minimumCost(
self,
source: str,
target: str,
original: List[str],
changed: List[str],
cost: List[int],
) -> int:
g = [[inf] * 26 for _ in range(26)]
for i in range(26):
g[i][i] = 0
for x, y, z in zip(original, changed, cost):
x = ord(x) - ord('a')
y = ord(y) - ord('a')
g[x][y] = min(g[x][y], z)
for k in range(26):
for i in range(26):
for j in range(26):
g[i][j] = min(g[i][j], g[i][k] + g[k][j])
ans = 0
for a, b in zip(source, target):
if a != b:
x, y = ord(a) - ord('a'), ord(b) - ord('a')
if g[x][y] >= inf:
return -1
ans += g[x][y]
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.