Edit Distance - Dynamic Programming - Leetcode 72 - Python

  Рет қаралды 142,322

NeetCode

NeetCode

Күн бұрын

Пікірлер: 144
@NeetCode
@NeetCode 3 жыл бұрын
💡 DP PLAYLIST: kzbin.info/www/bejne/bWTVZH6Nnqqpr80
@abhishekmukherjee7348
@abhishekmukherjee7348 3 жыл бұрын
Hey NeetCode, I really enjoy your explanations! Most channels and videos on coding do explain the algorithm before code, but they are not nearly as good, as you are with such a nuanced approach towards describing the intuition and the thought process behind the applicable algorithm. Please keep it up, this has potential to change lives!
@kwetuligee8087
@kwetuligee8087 3 жыл бұрын
Oh my, this is so sweet! Great explanation, I haven’t seen a clear and concise explanation for edit distance like this.
@Akshay.Ramanathan
@Akshay.Ramanathan 2 жыл бұрын
This is the sweetest explanation of DP in general and how the bottom up approach suggests itself. Thanks a lot for this.
@ChanChan-pg4wu
@ChanChan-pg4wu 2 жыл бұрын
DP problems have a lot of similarity, bottom up or top down. The difficult part is more on how to derive the relation equation to connect sub-problem to main problem. More like an IQ test. Thank you Neet for another excellent explanation video. Your code is also super clean, PEP stylish!
@ngalatalla4032
@ngalatalla4032 2 жыл бұрын
You are amazing man and a great teacher. I had never understood the logic of the insertion and delete part of this question but you explained it very logically and beautifully. This is the best channel on KZbin on how to approach and solve coding problems and coming out with an optimized solution. Continue the great work.
@hooriehmarefat5972
@hooriehmarefat5972 2 жыл бұрын
Your explanations are absolutely awesome! Thanks for creating such helpful content!
@MP-ny3ep
@MP-ny3ep Жыл бұрын
After listening to your solution , this problem feels more like a medium level problem. That's how good your explanation is. Thank you !
@arnabkar8792
@arnabkar8792 4 күн бұрын
This is crazy man, After thinking for half an hour, I had to create a whole system for this question. You explained it so casually.
@paradox2738
@paradox2738 2 жыл бұрын
dp = [[i+j for i in range(len(word2),-1,-1)] for j in range(len(word1),-1,-1)] this combines the first 3 loops into one
@priyanshudeep1008
@priyanshudeep1008 2 жыл бұрын
I don't even code in python, I learn a lot from your thinking process. big fan!!
@mnchester
@mnchester 2 жыл бұрын
Amazing explanation of what the insert, delete, and replace operations mean in terms of the indexes of the words!
@xinniu3145
@xinniu3145 2 жыл бұрын
Thanks for the explanation! So one of the key points is you don't need to change word1 and word2 in the function, just need to move i and j!
@technophile_
@technophile_ 4 ай бұрын
Hands down THE BEST EXPLANATION of the solution to this question in the ENTIRE PLANET! Couldn't have explained it any better! Thank you sooo much NeetCode!
@yuqian822
@yuqian822 2 жыл бұрын
I have to say that again... I LOVE NEETCODE!!!!! You are the FIRST one to look for whenever I am confused about an algo question.
@SeanKearney-g7d
@SeanKearney-g7d 2 ай бұрын
this video is a masterpiece. the intuition flow is perfection
@onemoretube
@onemoretube 2 жыл бұрын
I'm studying Comp Sci online due to covid and the recorded lecture on Dynamic Programming was a bit difficult to follow. A class mate recommended your video. I checked it out and was glad I did. Liked and subcribed. Thank you so much!
@L0ukh4ck5
@L0ukh4ck5 2 жыл бұрын
you really deserve being at G
@ytg6663
@ytg6663 Жыл бұрын
G ?
@suraj8092
@suraj8092 10 ай бұрын
​@@ytg6663google
@assgoblin3981
@assgoblin3981 9 ай бұрын
​@@ytg6663gock
@SowmyaMekala-t3j
@SowmyaMekala-t3j 8 ай бұрын
Google
@DonaldFranciszekTusk
@DonaldFranciszekTusk 7 ай бұрын
Wonderful explanation, but the 0 -> n approach makes for better code readability than n -> 0.
@chenbin0802
@chenbin0802 2 жыл бұрын
This helps me a lot, your explaination is very good. I don't think I can finish edit distance and BK-tree problem before I saw your video.
@dk20can86
@dk20can86 2 жыл бұрын
You can reduce the space complexity to O(len(word2)) or O(len(word1)) (depending on the shape of your rows) by having 2 rows in memory instead of a full grid, as you only ever need to depend on the next row.
@deadlyecho
@deadlyecho Жыл бұрын
Nice, you would have to just replace the old row values with the next row values one by one each time you decrement the column while traversing
@wat5931
@wat5931 Жыл бұрын
Insert and remove are functionally the same. If you always make word 1 longer than word 2 (by swapping if necessary), you can always use just insert or just remove
@sasageyo9571
@sasageyo9571 2 жыл бұрын
Great explanation ! Finally after scratching my head for 2 days, i understand and have an intuition for the algorithm !
@augustdanellhakansson7400
@augustdanellhakansson7400 2 жыл бұрын
Extremely well explained! Picture perfect tutorial!
@AshwaniSharma-of2nq
@AshwaniSharma-of2nq Жыл бұрын
Easy to understand explanation, clear, concise and to the point.
@jadenlin3724
@jadenlin3724 Жыл бұрын
Hey NeetCode, your code is the best. Your code always helps me understand how you solved the problem.
@yossarian2909
@yossarian2909 2 жыл бұрын
oh man you made it so easy to understand this.. I spent hours watching various videos and blogs but never understood it.. i think i understand it now..
@christinemello694
@christinemello694 4 ай бұрын
How on earth will I come up with that table logic in an interview? God bless me
@zaid6527
@zaid6527 9 ай бұрын
We can do this in O(word2.size()) space complexity, but just using 2 arrays instead of using a 2d, we can use prev and cur array to construct the answer from bottom to up, here's the code in cpp, class Solution { public: int minDistance(string word1, string word2) { int counter = 0; int sizes = word2.size(); vector prev(sizes+1); vector cur(sizes+1); for(int i=0; i=0; i--){ counter++; cur[sizes] = counter; for(int j=sizes-1; j>=0; j--){ if(word1[i] == word2[j]){ cur[j] = prev[j+1]; } else{ int curs = min(cur[j+1], prev[j+1]); cur[j] = min(curs, prev[j]); cur[j] += 1; } } prev = cur; } return prev[0]; } };
@clintondannolfo714
@clintondannolfo714 2 жыл бұрын
It makes sense after seeing the solution but before that it's not so obvious that editing, replacing and inserting is just an off by one lookup in the DP table.. thanks for the vid
@julesrules1
@julesrules1 Жыл бұрын
You never fails at giving me an awe moment. Thank you!
@NingenVRC
@NingenVRC 6 ай бұрын
kudos to you man, you explained it majestically, I hope you are pursuing some teaching career cause you really are amazing
@ax5344
@ax5344 3 жыл бұрын
You are the best! I usually browsing news in the morning, but your tutorial uploads changed that! Love the frequency recently! Is N queens on your target list? ;-)
@NeetCode
@NeetCode 3 жыл бұрын
Thanks! Yes, I plan on doing N-Queens soon.
@firezdog
@firezdog 8 ай бұрын
it's interesting that you go forward instead of backward. i always thought of going backward (from the empty strings up) -- maybe just the way the class i took was taught (i.e. you can do it by suffixes or prefixes)
@am_rxd
@am_rxd Жыл бұрын
nicely done i am learning through these videos cause I was not able to understand what to dointially no idea what can I do or not just doing hit and rum stuff thanks for this its help me understand what to start with and what kind of concept I would have to keep in tracjk while having something of this caliber it was quite a easy code but without this explanation of your I would never able to understand the the logic how to do .
@shiweiwong5292
@shiweiwong5292 2 жыл бұрын
the best explanation on the internet! thanks!
@dumdumbringgumgum2940
@dumdumbringgumgum2940 2 жыл бұрын
to everyone who feels DP is tough. Keep at it. One day it will suddenly click and it will be worth it. 💪
@theteacher010
@theteacher010 Жыл бұрын
Wouldn't have guessed this was LCS until you mentioned it!
@Sam-vi8iw
@Sam-vi8iw 2 жыл бұрын
Very clearly explained with code. Like it!
@shawn_yg1394
@shawn_yg1394 Жыл бұрын
Can not believe that it has been downgraded to a medium question. I have completely no idea the first time saw it lol.
@shivamsingh3727
@shivamsingh3727 2 жыл бұрын
That way it was explained is really impressive. Thanks a bunch!
@ivanchennyc
@ivanchennyc Ай бұрын
I think a cleaner answer would be class Solution: def minDistance(self, word1: str, word2: str) -> int: n = len(word1) m = len(word2) cache = [[float("inf")] * (m+1) for i in range(n+1) ] # base case for j in range(m+1): cache[0][j] = j for i in range(n+1): cache[i][0] = i for i in range(1,n+1): for j in range(1,m+1): if word1[i-1] == word2[j-1]: cache[i][j] = cache[i-1][j-1] else: cache[i][j] = 1 + min(cache[i-1][j],cache[i][j-1],cache[i-1][j-1])#insert, delete, replace return cache[n][m]
@jeremyliang7159
@jeremyliang7159 3 жыл бұрын
Pure art! Best explanation!
@amogchandrashekar8159
@amogchandrashekar8159 3 жыл бұрын
Awesome explaination as always 🙏
@river.
@river. Жыл бұрын
i am just so happy when i find your video
@sancho7198
@sancho7198 9 ай бұрын
class Solution: def minDistance(self, word1: str, word2: str) -> int: M, N=len(word2), len(word1) dp = [[-1] * (M+1) for _ in range(N+1)] for i in range(N + 1): dp[i][M] = N - i for j in range(M + 1): dp[N][j] = M - j def dfs(i, k): if dp[i][k] != -1: return dp[i][k] if word1[i]==word2[k]: dp[i][k]=dfs(i+1, k+1) else: dp[i][k]= 1 + min(dfs(i+1, k+1),#subtitution dfs(i+1, k), #delete dfs(i,k+1)) #insert return dp[i][k] return dfs(0,0) for me this was easier to understand, might help someone :)
@romo119
@romo119 Жыл бұрын
What's the purpose for initializing every elem to inf? Aren't we filling every element right to left, bottom up anyways? We just need to make sure the edges of the matrix are filled and solve the problem in the correct order, so the value at dp[i][j] can originally be 0
@dollyvishwakarma2
@dollyvishwakarma2 2 жыл бұрын
Super clear explanation! Kudos!
@mama1990ish
@mama1990ish 3 жыл бұрын
Please add the cherry pickup problem. Your DP solutions are simple and understandable especially the bottom up approaches.
@karavind7814
@karavind7814 2 жыл бұрын
Best explanation for edit distance
@abc00gh
@abc00gh 2 жыл бұрын
Best explanation for 2d dp ever!
@Raviranjankumar761
@Raviranjankumar761 Жыл бұрын
I'm stuck at why We cannot solve this problem with the LCS ? STEPS: 1. Find LCS of two strings. Let the length of LCS be x. 2. Let the length of the first string be m and the length of the second string be n. (m - x) will be the answer in that case.
@messi_codes
@messi_codes 2 жыл бұрын
GOD LEVEL EXPLANATION 😵
@konradhunter1407
@konradhunter1407 5 ай бұрын
😯 I never would have come up with this.
@thestarinthesky_
@thestarinthesky_ 2 жыл бұрын
Amazing! Great explanations have ever seen!
@nitin9042
@nitin9042 3 жыл бұрын
I love your explanation. Love u neetcode hope
@yang5843
@yang5843 Жыл бұрын
Elegant explanation, thank you
@sallaklamhayyen9876
@sallaklamhayyen9876 9 ай бұрын
a big thank for you , you are doing a great job ❤❤❤
@dataadvantage1890
@dataadvantage1890 2 жыл бұрын
try this --- for j in range(len(word1) + 1, -1, -1)
@yinglll7411
@yinglll7411 3 жыл бұрын
Again, thank you so much for this explanation, please keep it up!
@akhma102
@akhma102 2 ай бұрын
Thank you Neet!
@samaygandhi7182
@samaygandhi7182 2 жыл бұрын
Best explanation ever!
@feilianhuang4604
@feilianhuang4604 2 жыл бұрын
THAT IS BRILLIANT
@charlielin188
@charlielin188 2 жыл бұрын
Why cache[i+1, j+1] is always less or equal than (cache[i+1, j] + 1) and (cache[i, j+1] + 1) ?
@tanngo1564
@tanngo1564 2 жыл бұрын
I have same question 🤔
@arijaa.9315
@arijaa.9315 10 ай бұрын
I have noticed that the result does not change if we reverse the column and rows does that mean that converting word2 to word1 have the same distance as converting word1 to word2?
@edwardteach2
@edwardteach2 2 жыл бұрын
U a DP God
@arijaa.9315
@arijaa.9315 10 ай бұрын
Thanks! what do ou use the explain and draw on the screen?
@AdenGolden
@AdenGolden 2 жыл бұрын
for the else statement:cache[i + j] = 1 + min(cache[i][j + 1], cache[i+ 1][j], cache[i + 1][j +1]) why do we use 1+, where the 1 comes from? Thanks!
@anujchoudhary5645
@anujchoudhary5645 2 жыл бұрын
Best explanation as always
@chowtuk
@chowtuk Жыл бұрын
holy shit, things look so simple after this video
@blitz3106
@blitz3106 10 күн бұрын
Explicación perfecta!!!
@brawnybytes
@brawnybytes Жыл бұрын
Great explanation
@simbol5638
@simbol5638 9 ай бұрын
Thanks so much for your videos
@arnabpersonal6729
@arnabpersonal6729 3 жыл бұрын
Great explanation. Is there a possibility to optimize for space
@miladjamali5123
@miladjamali5123 2 жыл бұрын
thank you so much.could you help me how to use EDR on two point sets?
@kuangyimeng8850
@kuangyimeng8850 2 жыл бұрын
wow, brilliant explanation. Would you like to share how to come up with this idea?
@kumarvivek02
@kumarvivek02 2 жыл бұрын
hmm at 11:20, when you highlight cell 1,1, you're actually solving for substring "ab" for word1 & "ac" for word2. But you mention "bc" and "cd". Since this is solving for smaller problems first.
@kumarvivek02
@kumarvivek02 2 жыл бұрын
Also, shouldn't initialisation happen for row = 0 & col = 0, you seem to doing it inverted. for row + 1 & col + 1. Seems counter intuitive
@prayag_vaibhav
@prayag_vaibhav 2 жыл бұрын
Great video, helped a lot.
@ArcGaming07YT
@ArcGaming07YT Жыл бұрын
very helpful, thanks man
@ferb7o2
@ferb7o2 Жыл бұрын
Ok this is crazy
@DatascienceConcepts
@DatascienceConcepts 3 жыл бұрын
Excellent Content!
@jxw7196
@jxw7196 2 жыл бұрын
Brill. GOod job!
@Siddhii_
@Siddhii_ 2 жыл бұрын
I think instead of using a whole new 2d cache we can use two arrays, that way my acceptance is 84% and 95% respectively.
@yanjimmy8794
@yanjimmy8794 Жыл бұрын
Hi I have a question. I'm confused about why when word1[i] == word2[j] we need to use the diagonal value? How to find this pattern which is crucial to this problem. I'm new to dynamic programming. Hope someone can help. thanks in advance
@faranasiri3978
@faranasiri3978 8 ай бұрын
question, did you come up with this solution or you've seen this problem before? i really wonder how people come up with some solution for these hard questions, I'm sure i would be just staring at the interviewer if they ask me this on an interview and i've never seen this before
@dave6012
@dave6012 2 жыл бұрын
Have you ever done a “total unique combinations that add up to n” algorithm? I had that problem come up and I couldn’t write an algorithm efficient enough to pass all cases in the allotted time. It’s pretty wild, 200 ends up producing 487 million unique combinations. I know there must be a dynamic programming solution, but I couldn’t crack it.
@tommclean9208
@tommclean9208 Жыл бұрын
You need a way to stop searching for more candidates when you know a path will exceed the sum. I assume the values are all positive, which means if you add an item, the sum will only increase. This means, if you sort the array, you can start with the smallest values first and subtract from the target value, if the target goes negative then you no longer need to keep on searching for candidates. Here is some python code of the solution: class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: res = [] candidates.sort() def dfs(target, index, path): if target < 0: return if target == 0: res.append(path) return for i in range(index, len(candidates)): dfs(target-candidates[i], i, path+[candidates[i]]) dfs(target, 0, []) return res
@dave6012
@dave6012 Жыл бұрын
@@tommclean9208 thanks for taking the time to think about the problem and write your solution. I agree when you say I need a way to stop calculating when the candidates reach the sum. I created several working solutions that were unfortunately not fast enough. The only thing with your solution is it’s solving a slightly different problem. In the problem I was solving, we are not given a list of candidates, only a number that all combos must add up to. In addition, we only need to return the number of combinations. So essentially, 200 goes in, 487 million is returned. It’s terribly intensive, resource wise, and I sincerely doubt there a tidy solution for this, but open to finding out! I benchmarked my best solution, it was 5 minutes to calculate 200 🙃
@JustTrace17
@JustTrace17 Жыл бұрын
Thank you so much!
@xiaoweidu4667
@xiaoweidu4667 9 ай бұрын
great tutorial!
@deepika5880
@deepika5880 2 жыл бұрын
Very helpful 👍
@arjunv1624
@arjunv1624 3 жыл бұрын
subscribed
@emmatime2016
@emmatime2016 3 жыл бұрын
You are just great!!!!
@kirillzlobin7135
@kirillzlobin7135 11 ай бұрын
Hi NeetCode. What is your rank on leetcode?
@ramdamdam1402
@ramdamdam1402 6 ай бұрын
What is the formal explanation for why if the first two letters are equal then you can just solve the subproblems by deleting the first letters of each words. For all we know they may have been useful later no ? I find all explanations on youtube to be lack luster
@sumanth6299
@sumanth6299 2 жыл бұрын
This is called Excellence
@ZQutui
@ZQutui 3 жыл бұрын
Nice explanations. Btw, it can be solved using dfs + memoization with the same time + space complexity
@user-gq1ij
@user-gq1ij 2 жыл бұрын
Nice explanation, BTW you are Canadian lad
@hwang1607
@hwang1607 8 ай бұрын
What is the time complexity of this
@danielsun716
@danielsun716 Жыл бұрын
dp = {} def dfs(i, j): if i == len(word1) and j == len(word2): return 0 if i == len(word1): return len(word2) - j if j == len(word2): return len(word1) - i if (i, j) in dp: return dp[(i, j)] dp[(i, j)] = float("inf") for i in range(len(word1) - 1, -1, -1): for j in range(len(word2) - 1, -1, -1): if word1[i] == word2[j]: dp[(i, j)] = dfs(i + 1, j + 1) else: dp[(i, j)] = 1 + min(dfs(i, j + 1), dfs(i + 1, j), dfs(i + 1, j + 1)) return dp[(i, j)] return dfs(0, 0)
@begula_chan
@begula_chan 8 ай бұрын
Brooooo, thanks!
@hepbitkin9854
@hepbitkin9854 Жыл бұрын
I think you should draw rest of the problem.
Burst Baloons - Dynamic Programming - Leetcode 312 - Python
21:20
كم بصير عمركم عام ٢٠٢٥😍 #shorts #hasanandnour
00:27
hasan and nour shorts
Рет қаралды 10 МЛН
DP 33. Edit Distance | Recursive to 1D Array Optimised Solution 🔥
37:39
The Algorithm Behind Spell Checkers
13:02
b001
Рет қаралды 418 М.
Climbing Stairs - Dynamic Programming - Leetcode 70 - Python
18:08
Learn Python OOP in under 20 Minutes
18:32
Indently
Рет қаралды 110 М.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 584 М.
Lecture 21: Dynamic Programming III: Parenthesization, Edit Distance, Knapsack
52:41
Minimum edit distance | Dynamic programming | Backtracking
28:52
Unique Paths II - Leetcode 63 - Python
14:31
NeetCodeIO
Рет қаралды 18 М.
Улучшил свой айфон!
0:17
По ту сторону Гугла
Рет қаралды 5 МЛН
Как подключить магнитолу?
0:51
KS Customs
Рет қаралды 2,2 МЛН
Me Charging My Phone Before Going Out
0:18
Godfrey Twins
Рет қаралды 14 МЛН
Introducing the "VitaWear SmartBand," a next-generation wearable gadget
0:25
The Kaushal Official
Рет қаралды 2 МЛН
Наклейка SSD 💽
0:24
serg1us
Рет қаралды 530 М.