Magicsheet logo

Minimum Cost to Convert String II

Hard
58.7%
Updated 6/1/2025

Minimum Cost to Convert String II

What is this problem about?

Minimum Cost to Convert String II is a more complex version where transformations aren't just single characters, but entire substrings. You are given a set of original strings and their corresponding converted strings with a cost. You want to convert a source string to a target string by replacing non-overlapping substrings.

Why is this asked in interviews?

This is a high-difficulty Minimum Cost to Convert String interview question at Atlassian and Amazon. it combines Floyd-Warshall (for the transformation costs) with Dynamic Programming and Tries (to efficiently find valid substring matches). It tests a candidate's ability to integrate multiple data structures into a single solution.

Algorithmic pattern used

The DP with Trie and Floyd-Warshall interview pattern is required.

  1. Use a Trie to store all the original and converted substrings.
  2. Use Floyd-Warshall to find the minimum cost between any two strings in your set of "special" substrings.
  3. Use Dynamic Programming where dp[i] is the minimum cost to convert the prefix of length i.
  4. For each i, look for all substrings source[j...i] that match an entry in your Trie and update dp[i] accordingly.

Example explanation

Source: "abcdef", Target: "abcxyz". Rule: "def" -> "xyz" cost 10.

  1. dp[0...3] cost 0 (since they already match).
  2. At i=6, we find the substring "def" matches the target "xyz".
  3. dp[6] = min(dp[6], dp[3] + cost("def" -> "xyz")) = 10.

Common mistakes candidates make

  • Slow string matching: Using a simple O(N2)O(N^2) string comparison instead of a Trie or Aho-Corasick.
  • Ignoring multiple ways to convert: Not realizing a substring can be converted through multiple steps (e.g., "A" -> "B" -> "C").
  • State management: Forgetting to handle the case where characters already match (source[i] == target[i]).

Interview preparation tip

This problem is essentially "Segmenting a string optimally." Whenever you can break a string into pieces with associated costs, it's a Linear DP problem. The difficulty here is just in calculating the costs and finding the segments.

Similar Questions