Program to find minimum number of subsequence whose concatenation is same as target in python

PythonServer Side ProgrammingProgramming

Suppose we have two strings source and target, we have to find the minimum number of subsequences of source we can form such that if we concatenate them, it will be same as target. If there is no such result, return -1.

So, if the input is like source = "xyz" target = "xyzyzz", then the output will be 3, as we can concatenate these ["xyz" + "yz" + "z"]

To solve this, we will follow these steps −

  • s_size := size of s, t_size := size of t
  • concat_count := 0, target_idx := 0
  • while target_idx < t_size, do
    • source_idx := 0
    • temp_index := target_idx
    • while source_idx < s_size and target_idx < t_size, do
      • if s[source_idx] is same as t[target_idx], then
        • target_idx := target_idx + 1
      • source_idx := source_idx + 1
    • if temp_index is same as target_idx, then
      • return -1
    • concat_count := concat_count + 1
  • return concat_count

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, s, t):
      s_size, t_size = len(s), len(t)
      concat_count = 0
      target_idx = 0
      while target_idx < t_size:
         source_idx = 0
         temp_index = target_idx

         while source_idx < s_size and target_idx < t_size:
            if s[source_idx] == t[target_idx]:
               target_idx += 1
            source_idx += 1

         if temp_index == target_idx:
            return -1
         concat_count += 1
      return concat_count
ob = Solution()
source = "xyz"
target = "xyzyzz"
print(ob.solve(source, target))

Input

"xyz", "xyzyzz"

Output

3
raja
Published on 02-Dec-2020 05:04:32
Advertisements