Program to find minimum deletions to make strings strings in Python

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)


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
         if s[i] == t[j]:
            return dp(i + 1, j + 1)
            return 1 + min(dp(i + 1, j), dp(i, j + 1))
   return dp(0, 0)

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


"pipe", "ripe"



Updated on: 18-Oct-2021


Kickstart Your Career

Get certified by completing the course

Get Started