Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English characters. You are also given two 0-indexed string arrays original and changed, and an integer array cost, where cost[i] represents the cost of converting the string original[i] to the string changed[i].
You start with the string source. In one operation, you can pick a substring x from the string, and change it to y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions:
source[a..b] and source[c..d] with either b < c or d < a. In other words, the indices picked in both operations are disjoint.source[a..b] and source[c..d] with a == c and b == d. In other words, the indices picked in both operations are identical.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].
Example 1:
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 "abcd" to "acbe", do the following operations: - Change substring source[1..1] from "b" to "c" at a cost of 5. - Change substring source[2..2] from "c" to "e" at a cost of 1. - Change substring source[2..2] from "e" to "b" at a cost of 2. - Change substring source[3..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.
Example 2:
Input: source = "abcdefgh", target = "acdeeghh", original = ["bcd","fgh","thh"], changed = ["cde","thh","ghh"], cost = [1,3,5] Output: 9 Explanation: To convert "abcdefgh" to "acdeeghh", do the following operations: - Change substring source[1..3] from "bcd" to "cde" at a cost of 1. - Change substring source[5..7] from "fgh" to "thh" at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from "thh" to "ghh" at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost.
Example 3:
Input: source = "abcdefgh", target = "addddddd", original = ["bcd","defgh"], changed = ["ddd","ddddd"], cost = [100,1578] Output: -1 Explanation: It is impossible to convert "abcdefgh" to "addddddd". If you select substring source[1..3] as the first operation to change "abcdefgh" to "adddefgh", you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change "abcdefgh" to "abcddddd", you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation.
Constraints:
1 <= source.length == target.length <= 1000source, target consist only of lowercase English characters.1 <= cost.length == original.length == changed.length <= 1001 <= original[i].length == changed[i].length <= source.lengthoriginal[i], changed[i] consist only of lowercase English characters.original[i] != changed[i]1 <= cost[i] <= 106Problem summary: You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English characters. You are also given two 0-indexed string arrays original and changed, and an integer array cost, where cost[i] represents the cost of converting the string original[i] to the string changed[i]. You start with the string source. In one operation, you can pick a substring x from the string, and change it to y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions: The substrings picked in the operations are source[a..b] and source[c..d] with either b < c or d < a. In other words, the indices picked in both operations are disjoint. The substrings picked in the operations are source[a..b] and source[c..d]
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Trie
"abcd" "acbe" ["a","b","c","c","e","d"] ["b","c","b","e","b","e"] [2,5,5,1,2,20]
"abcdefgh" "acdeeghh" ["bcd","fgh","thh"] ["cde","thh","ghh"] [1,3,5]
"abcdefgh" "addddddd" ["bcd","defgh"] ["ddd","ddddd"] [100,1578]
can-convert-string-in-k-moves)minimum-moves-to-convert-string)minimum-number-of-valid-strings-to-form-target-ii)minimum-number-of-valid-strings-to-form-target-i)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2977: Minimum Cost to Convert String II
class Node {
Node[] children = new Node[26];
int v = -1;
}
class Solution {
private final long inf = 1L << 60;
private Node root = new Node();
private int idx;
private long[][] g;
private char[] s;
private char[] t;
private Long[] f;
public long minimumCost(
String source, String target, String[] original, String[] changed, int[] cost) {
int m = cost.length;
g = new long[m << 1][m << 1];
s = source.toCharArray();
t = target.toCharArray();
for (int i = 0; i < g.length; ++i) {
Arrays.fill(g[i], inf);
g[i][i] = 0;
}
for (int i = 0; i < m; ++i) {
int x = insert(original[i]);
int y = insert(changed[i]);
g[x][y] = Math.min(g[x][y], cost[i]);
}
for (int k = 0; k < idx; ++k) {
for (int i = 0; i < idx; ++i) {
if (g[i][k] >= inf) {
continue;
}
for (int j = 0; j < idx; ++j) {
g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
}
}
}
f = new Long[s.length];
long ans = dfs(0);
return ans >= inf ? -1 : ans;
}
private int insert(String w) {
Node node = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (node.children[i] == null) {
node.children[i] = new Node();
}
node = node.children[i];
}
if (node.v < 0) {
node.v = idx++;
}
return node.v;
}
private long dfs(int i) {
if (i >= s.length) {
return 0;
}
if (f[i] != null) {
return f[i];
}
long res = s[i] == t[i] ? dfs(i + 1) : inf;
Node p = root, q = root;
for (int j = i; j < s.length; ++j) {
p = p.children[s[j] - 'a'];
q = q.children[t[j] - 'a'];
if (p == null || q == null) {
break;
}
if (p.v < 0 || q.v < 0) {
continue;
}
long t = g[p.v][q.v];
if (t < inf) {
res = Math.min(res, t + dfs(j + 1));
}
}
return f[i] = res;
}
}
// Accepted solution for LeetCode #2977: Minimum Cost to Convert String II
type Node struct {
children [26]*Node
v int
}
func newNode() *Node {
return &Node{v: -1}
}
func minimumCost(source string, target string, original []string, changed []string, cost []int) int64 {
inf := 1 << 60
root := newNode()
idx := 0
m := len(cost)
g := make([][]int, m<<1)
for i := range g {
g[i] = make([]int, m<<1)
for j := range g[i] {
g[i][j] = inf
}
g[i][i] = 0
}
insert := func(w string) int {
node := root
for _, c := range w {
i := c - 'a'
if node.children[i] == nil {
node.children[i] = newNode()
}
node = node.children[i]
}
if node.v < 0 {
node.v = idx
idx++
}
return node.v
}
for i := range original {
x := insert(original[i])
y := insert(changed[i])
g[x][y] = min(g[x][y], cost[i])
}
for k := 0; k < idx; k++ {
for i := 0; i < idx; i++ {
if g[i][k] >= inf {
continue
}
for j := 0; j < idx; j++ {
g[i][j] = min(g[i][j], g[i][k]+g[k][j])
}
}
}
n := len(source)
f := make([]int, n)
for i := range f {
f[i] = -1
}
var dfs func(int) int
dfs = func(i int) int {
if i >= n {
return 0
}
if f[i] >= 0 {
return f[i]
}
f[i] = inf
if source[i] == target[i] {
f[i] = dfs(i + 1)
}
p, q := root, root
for j := i; j < n; j++ {
p = p.children[source[j]-'a']
q = q.children[target[j]-'a']
if p == nil || q == nil {
break
}
if p.v < 0 || q.v < 0 {
continue
}
f[i] = min(f[i], dfs(j+1)+g[p.v][q.v])
}
return f[i]
}
ans := dfs(0)
if ans >= inf {
ans = -1
}
return int64(ans)
}
# Accepted solution for LeetCode #2977: Minimum Cost to Convert String II
class Node:
__slots__ = ["children", "v"]
def __init__(self):
self.children: List[Node | None] = [None] * 26
self.v = -1
class Solution:
def minimumCost(
self,
source: str,
target: str,
original: List[str],
changed: List[str],
cost: List[int],
) -> int:
m = len(cost)
g = [[inf] * (m << 1) for _ in range(m << 1)]
for i in range(m << 1):
g[i][i] = 0
root = Node()
idx = 0
def insert(w: str) -> int:
node = root
for c in w:
i = ord(c) - ord("a")
if node.children[i] is None:
node.children[i] = Node()
node = node.children[i]
if node.v < 0:
nonlocal idx
node.v = idx
idx += 1
return node.v
@cache
def dfs(i: int) -> int:
if i >= len(source):
return 0
res = dfs(i + 1) if source[i] == target[i] else inf
p = q = root
for j in range(i, len(source)):
p = p.children[ord(source[j]) - ord("a")]
q = q.children[ord(target[j]) - ord("a")]
if p is None or q is None:
break
if p.v < 0 or q.v < 0:
continue
res = min(res, dfs(j + 1) + g[p.v][q.v])
return res
for x, y, z in zip(original, changed, cost):
x = insert(x)
y = insert(y)
g[x][y] = min(g[x][y], z)
for k in range(idx):
for i in range(idx):
if g[i][k] >= inf:
continue
for j in range(idx):
# g[i][j] = min(g[i][j], g[i][k] + g[k][j])
if g[i][k] + g[k][j] < g[i][j]:
g[i][j] = g[i][k] + g[k][j]
ans = dfs(0)
return -1 if ans >= inf else ans
// Accepted solution for LeetCode #2977: Minimum Cost to Convert String II
use std::cmp::min;
struct Node {
children: [Option<Box<Node>>; 26],
v: i32,
}
impl Node {
fn new() -> Self {
Self {
children: std::array::from_fn(|_| None),
v: -1,
}
}
}
impl Solution {
pub fn minimum_cost(
source: String,
target: String,
original: Vec<String>,
changed: Vec<String>,
cost: Vec<i32>,
) -> i64 {
let inf: i64 = 1 << 60;
let mut root = Box::new(Node::new());
let mut idx: usize = 0;
let m = cost.len();
let n = m << 1;
let mut g = vec![vec![inf; n]; n];
for i in 0..n {
g[i][i] = 0;
}
let mut insert = |w: &str, root: &mut Box<Node>, idx: &mut usize| -> usize {
let mut node: &mut Box<Node> = root;
for c in w.bytes() {
let i = (c - b'a') as usize;
if node.children[i].is_none() {
node.children[i] = Some(Box::new(Node::new()));
}
node = node.children[i].as_mut().unwrap();
}
if node.v < 0 {
node.v = *idx as i32;
*idx += 1;
}
node.v as usize
};
for i in 0..m {
let x = insert(&original[i], &mut root, &mut idx);
let y = insert(&changed[i], &mut root, &mut idx);
g[x][y] = min(g[x][y], cost[i] as i64);
}
for k in 0..idx {
for i in 0..idx {
if g[i][k] >= inf {
continue;
}
for j in 0..idx {
let v = g[i][k] + g[k][j];
if v < g[i][j] {
g[i][j] = v;
}
}
}
}
let s = source.into_bytes();
let t = target.into_bytes();
let len = s.len();
let mut f: Vec<Option<i64>> = vec![None; len];
fn dfs(
i: usize,
s: &[u8],
t: &[u8],
root: &Box<Node>,
g: &Vec<Vec<i64>>,
f: &mut Vec<Option<i64>>,
inf: i64,
) -> i64 {
if i >= s.len() {
return 0;
}
if let Some(v) = f[i] {
return v;
}
let mut res = if s[i] == t[i] {
dfs(i + 1, s, t, root, g, f, inf)
} else {
inf
};
let mut p: Option<&Box<Node>> = Some(root);
let mut q: Option<&Box<Node>> = Some(root);
for j in i..s.len() {
p = p.and_then(|x| x.children[(s[j] - b'a') as usize].as_ref());
q = q.and_then(|x| x.children[(t[j] - b'a') as usize].as_ref());
if p.is_none() || q.is_none() {
break;
}
let pv = p.unwrap().v;
let qv = q.unwrap().v;
if pv < 0 || qv < 0 {
continue;
}
let c = g[pv as usize][qv as usize];
if c < inf {
let v = c + dfs(j + 1, s, t, root, g, f, inf);
if v < res {
res = v;
}
}
}
f[i] = Some(res);
res
}
let ans = dfs(0, &s, &t, &root, &g, &mut f, inf);
if ans >= inf { -1 } else { ans }
}
}
// Accepted solution for LeetCode #2977: Minimum Cost to Convert String II
class Node {
children: (Node | null)[] = Array(26).fill(null);
v: number = -1;
}
function minimumCost(
source: string,
target: string,
original: string[],
changed: string[],
cost: number[],
): number {
const m = cost.length;
const n = source.length;
const g: number[][] = Array.from({ length: m << 1 }, () => Array(m << 1).fill(Infinity));
const root: Node = new Node();
let idx: number = 0;
const f: number[] = Array(n).fill(-1);
const insert = (w: string): number => {
let node: Node = root;
for (const c of w) {
const i: number = c.charCodeAt(0) - 'a'.charCodeAt(0);
if (node.children[i] === null) {
node.children[i] = new Node();
}
node = node.children[i] as Node;
}
if (node.v < 0) {
node.v = idx++;
}
return node.v;
};
const dfs = (i: number): number => {
if (i >= n) {
return 0;
}
if (f[i] !== -1) {
return f[i];
}
let res: number = source[i] === target[i] ? dfs(i + 1) : Infinity;
let p: Node = root;
let q: Node = root;
for (let j = i; j < source.length; ++j) {
p = p.children[source[j].charCodeAt(0) - 'a'.charCodeAt(0)] as Node;
q = q.children[target[j].charCodeAt(0) - 'a'.charCodeAt(0)] as Node;
if (p === null || q === null) {
break;
}
if (p.v < 0 || q.v < 0) {
continue;
}
const t: number = g[p.v][q.v];
res = Math.min(res, t + dfs(j + 1));
}
return (f[i] = res);
};
for (let i = 0; i < m; ++i) {
const x: number = insert(original[i]);
const y: number = insert(changed[i]);
g[x][y] = Math.min(g[x][y], cost[i]);
}
for (let k = 0; k < idx; ++k) {
for (let i = 0; i < idx; ++i) {
if (g[i][k] >= Infinity) {
continue;
}
for (let j = 0; j < idx; ++j) {
g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
}
}
}
const ans: number = dfs(0);
return ans >= Infinity ? -1 : ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.