input: from typing import List
  from random import randint
  from collections import defaultdict
  from math import inf
  
  def minimum_cost_to_form_string(target: str, words: List[str], costs: List[int]) -> int:
      """
      Given a string target, an array of strings words, and an array of integers costs with the same length.
  
      Start with an empty string s.
  
      The following operation can be performed any number of times (including zero):
      
      Choose an index i in the range [0, words.length - 1].
      Append words[i] to s.
      The cost of operation is costs[i].
      
      Return the minimal cost to transform s into target. Return -1 if it is not feasible.
  
      Examples:
      >>> target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]
      7
      >>> target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]
      -1
  
      Constraints:
      1 <= target.length <= 5 * 10^4
      1 <= words.length == costs.length <= 5 * 10^4
      1 <= words[i].length <= target.length
      The total sum of words[i].length is less than or equal to 5 * 10^4.
      Target and words[i] consist only of lowercase English letters.
      1 <= costs[i] <= 10^4
      """
output:     dp = [inf] * (len(target) + 1)
      dp[0] = 0
  
      # Write a list of possible start positions for each word
      valid_starts = defaultdict(list)
      for i, word in enumerate(words):
          loc = target.find(word)
          while loc != -1:
              valid_starts[loc].append(i)
              loc = target.find(word, loc + 1)
  
      # Dynamic programming to compute minimum cost to form each prefix of the target
      for i in range(len(target)):
          if dp[i] == inf:
              continue  # Skip if this prefix cannot be formed
          for j in valid_starts[i]:
              word_len = len(words[j])
              cost = costs[j]
              if i + word_len <= len(target) and target[i:i + word_len] == words[j]:
                  dp[i + word_len] = min(dp[i + word_len], dp[i] + cost)
  
      # The answer is the minimum cost to form the entire target string
      return -1 if dp[len(target)] == inf else dp[len(target)]