Program to find minimum deletions to make strings strings in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lowercase strings s and t, now consider an operation where we can delete any character in any of these two strings. We have to find the minimum number of operations needed to make s and t equal.

So, if the input is like s = "pipe" t = "ripe", then the output will be 2, because we can delete "p" from s and "r" from t to make these strings same "ipe"

To solve this, we will follow these steps −

  • m := size of s
  • n := size of t
  • Define a function dp() . This will take i, j
  • if i is same as m, then
    • return n - j
  • otherwise when j is same as n, then
    • return m - i
  • otherwise,
    • if s[i] is same as t[j], then
      • return dp(i + 1, j + 1)
    • otherwise,
      • return 1 + (minimum of dp(i + 1, j) and dp(i, j + 1))
  • From the main method, return dp(0, 0)

Example

Let us see the following implementation to get better understanding −

def solve(s, t):
   m = len(s)
   n = len(t)

   def dp(i, j):
      if i == m:
         return n - j
      elif j == n:
         return m - i
      else:
         if s[i] == t[j]:
            return dp(i + 1, j + 1)
         else:
            return 1 + min(dp(i + 1, j), dp(i, j + 1))
   return dp(0, 0)

s = "pipe"
t = "ripe"
print(solve(s, t))

Input

"pipe", "ripe"

Output

2
raja
Published on 18-Oct-2021 12:13:18
Advertisements