You are given two 0-indexed stringssource and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arraysoriginal and changed, and an integer arraycost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].
You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.
Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
💡 Note:We need to convert position 1: b→c (cost 5) and position 3: d→e (cost 20). The Floyd-Warshall algorithm finds these are the optimal paths. Total cost = 5 + 20 = 25.
💡 Note:We can convert a→c (cost 1) then c→b (cost 2), so each 'a' converts to 'b' with total cost 3. Since we need to convert 4 characters, total cost is 4 × 3 = 12.
The key insight is modeling character conversions as a weighted graph and finding shortest paths. The optimal Floyd-Warshall approach precomputes all shortest paths between character pairs in O(26³) time, then answers each query in O(1). Time: O(26³ + n), Space: O(26²)
Common Approaches
✓
Brute Force DFS
⏱️ Time: O(n × 26^k)
Space: O(k)
For each position where source and target differ, use depth-first search to find the minimum cost path from source character to target character. This explores all possible conversion sequences.
Floyd-Warshall All-Pairs Shortest Path
⏱️ Time: O(26³ + n)
Space: O(26²)
Build a graph of character conversions and use Floyd-Warshall algorithm to find shortest paths between all pairs of characters. Then for each character difference, lookup the precomputed minimum cost.
Brute Force DFS — Algorithm Steps
For each character position, check if conversion is needed
Use DFS to explore all possible conversion paths
Return minimum cost or -1 if impossible
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Input Analysis
Compare source and target, identify differences
2
DFS Exploration
For each difference, recursively try all conversion paths
3
Result
Return minimum total cost or -1 if impossible
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_EDGES 1000
#define MAX_LEN 1000
struct Edge {
char to;
int cost;
};
struct Graph {
struct Edge edges[26][MAX_EDGES];
int count[26];
};
long long dfs(char start, char end, int visited[26], struct Graph* graph) {
if (start == end) return 0;
int startIdx = start - 'a';
if (visited[startIdx]) return LLONG_MAX;
visited[startIdx] = 1;
long long minCost = LLONG_MAX;
for (int i = 0; i < graph->count[startIdx]; i++) {
char nextChar = graph->edges[startIdx][i].to;
int edgeCost = graph->edges[startIdx][i].cost;
long long subCost = dfs(nextChar, end, visited, graph);
if (subCost != LLONG_MAX) {
long long totalCost = (long long)edgeCost + subCost;
if (totalCost < minCost) {
minCost = totalCost;
}
}
}
visited[startIdx] = 0;
return minCost;
}
long long solution(char* source, char* target, char* original, char* changed, int* cost, int numConversions) {
if (strlen(source) != strlen(target)) return -1;
struct Graph graph;
memset(&graph, 0, sizeof(graph));
for (int i = 0; i < numConversions; i++) {
int fromIdx = original[i] - 'a';
graph.edges[fromIdx][graph.count[fromIdx]].to = changed[i];
graph.edges[fromIdx][graph.count[fromIdx]].cost = cost[i];
graph.count[fromIdx]++;
}
long long totalCost = 0;
int len = strlen(source);
for (int i = 0; i < len; i++) {
if (source[i] != target[i]) {
int visited[26] = {0};
long long costToConvert = dfs(source[i], target[i], visited, &graph);
if (costToConvert == LLONG_MAX) return -1;
totalCost += costToConvert;
}
}
return totalCost;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char source[MAX_LEN], target[MAX_LEN];
char original[MAX_EDGES], changed[MAX_EDGES];
int cost[MAX_EDGES];
fgets(source, sizeof(source), stdin);
source[strcspn(source, "\n")] = 0;
fgets(target, sizeof(target), stdin);
target[strcspn(target, "\n")] = 0;
// Simple parsing for arrays - assumes well-formed input
char line[MAX_LEN * 10];
fgets(line, sizeof(line), stdin);
int numConversions = 0;
char* token = strtok(line, "[,]");
while (token != NULL) {
if (token[0] == '"' && token[2] == '"') {
original[numConversions++] = token[1];
}
token = strtok(NULL, "[,]");
}
fgets(line, sizeof(line), stdin);
int idx = 0;
token = strtok(line, "[,]");
while (token != NULL) {
if (token[0] == '"' && token[2] == '"') {
changed[idx++] = token[1];
}
token = strtok(NULL, "[,]");
}
fgets(line, sizeof(line), stdin);
idx = 0;
token = strtok(line, "[,]");
while (token != NULL) {
if (token[0] >= '0' && token[0] <= '9') {
cost[idx++] = atoi(token);
}
token = strtok(NULL, "[,]");
}
printf("%lld\n", solution(source, target, original, changed, cost, numConversions));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n × 26^k)
For each of n characters, DFS can explore up to 26^k paths where k is conversion depth
n
2n
✓ Linear Growth
Space Complexity
O(k)
Recursion stack depth for DFS traversal
n
2n
✓ Linear Space
12.4K Views
MediumFrequency
~25 minAvg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.