#2976

Minimum Cost to Convert String I

Medium
ArrayStringGraph TheoryShortest PathGraph TheoryDijkstra's Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach constructs a graph where each character is a node and transformations are edges with weights. By using Dijkstra's algorithm, we can efficiently find the minimum cost to convert each character in the source string to the corresponding character in the target string.

⚙️

Algorithm

3 steps
  1. 1Step 1: Construct a graph where each character is a node and edges represent possible transformations with their associated costs.
  2. 2Step 2: For each character pair (source[i], target[i]), use Dijkstra's algorithm to find the minimum cost path from source[i] to target[i].
  3. 3Step 3: Sum the costs for all character transformations. If any transformation is impossible, return -1.
solution.py38 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def minCost(source, target, original, changed, cost):
6    graph = defaultdict(dict)
7    for i in range(len(original)):
8        if changed[i] not in graph[original[i]]:
9            graph[original[i]][changed[i]] = cost[i]
10        else:
11            graph[original[i]][changed[i]] = min(graph[original[i]][changed[i]], cost[i])
12
13    total_cost = 0
14    for s, t in zip(source, target):
15        if s == t:
16            continue
17        min_cost = dijkstra(graph, s, t)
18        if min_cost == float('inf'):
19            return -1
20        total_cost += min_cost
21    return total_cost
22
23
24def dijkstra(graph, start, end):
25    pq = [(0, start)]
26    min_cost = {start: 0}
27    while pq:
28        cost, node = heapq.heappop(pq)
29        if node == end:
30            return cost
31        for neighbor, weight in graph[node].items():
32            new_cost = cost + weight
33            if new_cost < min_cost.get(neighbor, float('inf')):
34                min_cost[neighbor] = new_cost
35                heapq.heappush(pq, (new_cost, neighbor))
36    return float('inf')
37
38print(minCost('abcd', 'acbe', ['a','b','c','c','e','d'], ['b','c','b','e','b','e'], [2,5,5,1,2,20]))

Complexity note: The time complexity is O(n log n) due to the priority queue operations in Dijkstra's algorithm, which is more efficient than the brute-force approach. The space complexity is O(n) for storing the graph and the minimum costs.

  • 1Constructing a graph helps visualize transformations and their costs.
  • 2Using Dijkstra's algorithm optimizes the search for minimum costs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.