Skip to content

Commit ef259b7

Browse files
committed
add Python/Delete_Operation_for_Two_Strings.py
1 parent fb39a19 commit ef259b7

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Question: Given two strings find the minimum number of letters you need to delete from each to get the same strings
2+
# Solution: Implement a top down or bottom up DP
3+
# Difficulty: Medium
4+
5+
def minDistance(w1: str, w2: str, store={}) -> int:
6+
# Our base cases are, if both strings are the same (this includes when they're both null) return 0 because nothing needs to be
7+
# deleted, if only one of them is non-null, then return the length of it since everything needs to be deleted
8+
if w1 == w2: return 0
9+
if not w1 or not w2: return len(w1 or w2)
10+
11+
# If we have this pair of words in our store then just return the deletion distance from that
12+
if (w1,w2) in store: return store[(w1,w2)]
13+
14+
# If both words start with the same letter, nothing needs to be deleted, so just rerun the function
15+
# on the substrings with the first character removed, otherwise try deleting the first letter from each word
16+
# and seeing which one results in the shorter deletion distance
17+
if w1[0] == w2[0]:
18+
edit = self.minDistance(w1[1:], w2[1:], store)
19+
else:
20+
edit = 1 + min(self.minDistance(w1[1:], w2, store), self.minDistance(w1, w2[1:], store))
21+
22+
# Once the computation is completed, store
23+
store[(w1,w2)] = edit
24+
return edit

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@
131131
| Climbing Stairs | 1 | 70 | Easy | Dynamic Programming | [Python](Python/Coin_Change.py) |
132132
| Coin Change | 2 | 518 | Medium | Dynamic Programming | [Python](Python/Number_Of_Islands.py) |
133133
| Decode Ways | 3 | 91 | Medium | Dynamic Programming | [Python](Python/Decode_Ways.py) |
134+
| Delete Operation for Two Strings | 4 | [583](https://leetcode.com/problems/delete-operation-for-two-strings/) | Medium | Dynamic Programming | [Python](Python/Delete_Operation_for_Two_Strings.py) |
135+
134136

135137
## 🎨 Design
136138
| Title | Reccomended Order # | Leetcode # | Difficulty | Tags | Solution |

0 commit comments

Comments
 (0)