Edit Distance - Dynamic Programming - Leetcode 72 - Python

Поделиться
HTML-код
  • Опубликовано: 30 июн 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    Problem Link: neetcode.io/problems/edit-dis...
    0:00 - Read the problem
    1:28 - Explaining Intuition
    10:40 - Drawing Explanation
    15:28 - Coding Explanation
    leetcode 72
    This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
    #edit #distance #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • НаукаНаука

Комментарии • 135

  • @NeetCode
    @NeetCode  3 года назад +15

    💡 DP PLAYLIST: ruclips.net/video/73r3KWiEvyk/видео.html

  • @kwetuligee8087
    @kwetuligee8087 3 года назад +57

    Oh my, this is so sweet! Great explanation, I haven’t seen a clear and concise explanation for edit distance like this.

  • @abhishekmukherjee7348
    @abhishekmukherjee7348 3 года назад +38

    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!

  • @hooriehmarefat5972
    @hooriehmarefat5972 Год назад +31

    Your explanations are absolutely awesome! Thanks for creating such helpful content!

  • @Akshay.Ramanathan
    @Akshay.Ramanathan 2 года назад +12

    This is the sweetest explanation of DP in general and how the bottom up approach suggests itself. Thanks a lot for this.

  • @ngalatalla4032
    @ngalatalla4032 2 года назад +10

    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 RUclips on how to approach and solve coding problems and coming out with an optimized solution. Continue the great work.

  • @mnchester
    @mnchester 2 года назад +4

    Amazing explanation of what the insert, delete, and replace operations mean in terms of the indexes of the words!

  • @chenbin0802
    @chenbin0802 2 года назад +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.

  • @ChanChan-pg4wu
    @ChanChan-pg4wu 2 года назад +13

    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!

  • @sasageyo9571
    @sasageyo9571 2 года назад +1

    Great explanation !
    Finally after scratching my head for 2 days, i understand and have an intuition for the algorithm !

  • @yuqian822
    @yuqian822 Год назад

    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.

  • @MP-ny3ep
    @MP-ny3ep Год назад +1

    After listening to your solution , this problem feels more like a medium level problem. That's how good your explanation is. Thank you !

  • @onemoretube
    @onemoretube 2 года назад +1

    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!

  • @priyanshudeep1008
    @priyanshudeep1008 2 года назад +3

    I don't even code in python, I learn a lot from your thinking process. big fan!!

  • @augustdanellhakansson7400
    @augustdanellhakansson7400 Год назад +3

    Extremely well explained! Picture perfect tutorial!

  • @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..

  • @shivamsingh3727
    @shivamsingh3727 2 года назад

    That way it was explained is really impressive. Thanks a bunch!

  • @xinniu3145
    @xinniu3145 2 года назад +1

    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!

  • @AshwaniSharma-of2nq
    @AshwaniSharma-of2nq Год назад

    Easy to understand explanation, clear, concise and to the point.

  • @julesrules1
    @julesrules1 11 месяцев назад

    You never fails at giving me an awe moment. Thank you!

  • @jadenlin3724
    @jadenlin3724 7 месяцев назад

    Hey NeetCode, your code is the best. Your code always helps me understand how you solved the problem.

  • @am_rxd
    @am_rxd 8 месяцев назад

    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 .

  • @Sam-vi8iw
    @Sam-vi8iw 2 года назад

    Very clearly explained with code. Like it!

  • @ax5344
    @ax5344 3 года назад +5

    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 года назад +1

      Thanks! Yes, I plan on doing N-Queens soon.

  • @yinglll7411
    @yinglll7411 3 года назад

    Again, thank you so much for this explanation, please keep it up!

  • @jeremyliang7159
    @jeremyliang7159 2 года назад +1

    Pure art! Best explanation!

  • @amogchandrashekar8159
    @amogchandrashekar8159 3 года назад +3

    Awesome explaination as always 🙏

  • @NingenVRC
    @NingenVRC Месяц назад

    kudos to you man, you explained it majestically, I hope you are pursuing some teaching career cause you really are amazing

  • @dollyvishwakarma2
    @dollyvishwakarma2 2 года назад

    Super clear explanation! Kudos!

  • @thestarinthesky_
    @thestarinthesky_ 2 года назад

    Amazing! Great explanations have ever seen!

  • @shiweiwong5292
    @shiweiwong5292 Год назад

    the best explanation on the internet! thanks!

  • @theteacher010
    @theteacher010 8 месяцев назад

    Wouldn't have guessed this was LCS until you mentioned it!

  • @prayag_vaibhav
    @prayag_vaibhav 2 года назад

    Great video, helped a lot.

  • @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

  • @yang5843
    @yang5843 Год назад

    Elegant explanation, thank you

  • @DatascienceConcepts
    @DatascienceConcepts 2 года назад

    Excellent Content!

  • @sallaklamhayyen9876
    @sallaklamhayyen9876 4 месяца назад

    a big thank for you , you are doing a great job ❤❤❤

  • @nitin9042
    @nitin9042 2 года назад

    I love your explanation. Love u neetcode hope

  • @river.
    @river. 11 месяцев назад

    i am just so happy when i find your video

  • @firezdog
    @firezdog 3 месяца назад

    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)

  • @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

  • @ArcGaming07YT
    @ArcGaming07YT Год назад

    very helpful, thanks man

  • @feilianhuang4604
    @feilianhuang4604 2 года назад

    THAT IS BRILLIANT

  • @abc00gh
    @abc00gh Год назад

    Best explanation for 2d dp ever!

  • @emmatime2016
    @emmatime2016 2 года назад

    You are just great!!!!

  • @JustTrace17
    @JustTrace17 Год назад

    Thank you so much!

  • @konradhunter1407
    @konradhunter1407 26 дней назад

    😯 I never would have come up with this.

  • @jxw7196
    @jxw7196 Год назад

    Brill. GOod job!

  • @L0ukh4ck5
    @L0ukh4ck5 2 года назад +11

    you really deserve being at G

  • @karavind7814
    @karavind7814 2 года назад

    Best explanation for edit distance

  • @samaygandhi7182
    @samaygandhi7182 2 года назад

    Best explanation ever!

  • @xiaoweidu4667
    @xiaoweidu4667 4 месяца назад

    great tutorial!

  • @mama1990ish
    @mama1990ish 2 года назад

    Please add the cherry pickup problem. Your DP solutions are simple and understandable especially the bottom up approaches.

  • @simbol5638
    @simbol5638 4 месяца назад

    Thanks so much for your videos

  • @paradox2738
    @paradox2738 Год назад +1

    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

  • @anujchoudhary5645
    @anujchoudhary5645 2 года назад

    Best explanation as always

  • @arnabpersonal6729
    @arnabpersonal6729 3 года назад

    Great explanation. Is there a possibility to optimize for space

  • @hudsonvan4322
    @hudsonvan4322 Год назад

    真的讚

  • @begula_chan
    @begula_chan 3 месяца назад

    Brooooo, thanks!

  • @dk20can86
    @dk20can86 2 года назад +1

    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

  • @deepika5880
    @deepika5880 2 года назад

    Very helpful 👍

  • @brawnybytes
    @brawnybytes Год назад

    Great explanation

  • @edwardteach2
    @edwardteach2 2 года назад +1

    U a DP God

  • @messi_codes
    @messi_codes 2 года назад +1

    GOD LEVEL EXPLANATION 😵

  • @kuangyimeng8850
    @kuangyimeng8850 Год назад

    wow, brilliant explanation. Would you like to share how to come up with this idea?

  • @DonaldFranciszekTusk
    @DonaldFranciszekTusk 2 месяца назад

    Wonderful explanation, but the 0 -> n approach makes for better code readability than n -> 0.

  • @arjunv1624
    @arjunv1624 3 года назад +1

    subscribed

  • @ferb7o2
    @ferb7o2 Год назад +2

    Ok this is crazy

  • @arijaa.9315
    @arijaa.9315 5 месяцев назад

    Thanks! what do ou use the explain and draw on the screen?

  • @MrPhantomYT7
    @MrPhantomYT7 3 года назад

    Awesome

  • @miladjamali5123
    @miladjamali5123 Год назад

    thank you so much.could you help me how to use EDR on two point sets?

  • @dumdumbringgumgum2940
    @dumdumbringgumgum2940 2 года назад +1

    to everyone who feels DP is tough. Keep at it. One day it will suddenly click and it will be worth it. 💪

  • @arijaa.9315
    @arijaa.9315 5 месяцев назад

    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?

  • @chowtuk
    @chowtuk Год назад

    holy shit, things look so simple after this video

  • @shawn_yg1394
    @shawn_yg1394 11 месяцев назад +2

    Can not believe that it has been downgraded to a medium question. I have completely no idea the first time saw it lol.

  • @dataadvantage1890
    @dataadvantage1890 Год назад

    try this --- for j in range(len(word1) + 1, -1, -1)

  • @hoyinli7462
    @hoyinli7462 2 года назад

    ure really legendary

  • @joshkjoby8400
    @joshkjoby8400 Год назад

    this is crazy

  • @AdenGolden
    @AdenGolden Год назад

    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!

  • @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

  • @amansinghal2431
    @amansinghal2431 23 дня назад

    Daaammmmnnn

  • @user-gq1ij
    @user-gq1ij Год назад

    Nice explanation, BTW you are Canadian lad

  • @lucamantova3070
    @lucamantova3070 2 года назад +2

    How do they expect me to know this? Lololol

    • @lucamantova3070
      @lucamantova3070 2 года назад

      They don’t. They expect me to have it memorized from a book lolol

    • @ersinerdem7285
      @ersinerdem7285 2 года назад

      I learnt that this is a well known question which is taught at the start of NLP lessons. From its number "72", can see that it is an old question and known for quite some time. But yeah, even if we know the solution, explaning the thought process in an interview is tricky.

  • @zaid6527
    @zaid6527 5 месяцев назад

    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];
    }
    };

  • @ZQutui
    @ZQutui 3 года назад

    Nice explanations. Btw, it can be solved using dfs + memoization with the same time + space complexity

  • @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.

  • @charlielin188
    @charlielin188 2 года назад +1

    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 Год назад

      I have same question 🤔

  • @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

  • @yanjimmy8794
    @yanjimmy8794 11 месяцев назад

    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

  • @dave6012
    @dave6012 Год назад

    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 🙃

  • @ShailPM
    @ShailPM Месяц назад

    does the goat respond

  • @vickyarora7380
    @vickyarora7380 2 года назад

    LEgenday explanation

  • @sumanth6299
    @sumanth6299 Год назад

    This is called Excellence

  • @chaitanyanimma2939
    @chaitanyanimma2939 3 года назад

    Hey,can you make a video on burst balloons (LC 312) anytime soon?

    • @NeetCode
      @NeetCode  3 года назад +1

      Sure, I'll try to do that soon.

  • @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.

  • @hepbitkin9854
    @hepbitkin9854 Год назад

    I think you should draw rest of the problem.

  • @hwang1607
    @hwang1607 3 месяца назад

    What is the time complexity of this

  • @kirillzlobin7135
    @kirillzlobin7135 6 месяцев назад

    Hi NeetCode. What is your rank on leetcode?

  • @messi_codes
    @messi_codes 2 года назад +1

  • @sagarchawla4926
    @sagarchawla4926 11 месяцев назад

    After watching you explanation, me be like - isn't there any hard dp problem on leetcode 🤣