Knuth-Morris-Pratt KMP - Find the Index of the First Occurrence in a String - Leetcode 28 - Python

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🥷 Discord: / discord
    🐦 Twitter: / neetcode1
    🐮 Support the channel: / neetcode
    CODE ON GITHUB: github.com/neetcode-gh/leetco...
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    💡 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 - ...
    💡 BINARY SEARCH PLAYLIST: • Binary Search
    📚 STACK PLAYLIST: • Stack Problems
    Problem Link: leetcode.com/problems/impleme...
    0:00 - Read the problem
    1:00 - Review Brute Force O(n * m)
    3:45 - Motivation for KMP
    5:25 - Understanding LPS
    9:15 - Coding LPS
    26:35 - Coding KMP
    leetcode 28
    This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
    #kmp #knuth-morris-pratt #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 159

  • @NeetCode
    @NeetCode  Před 2 lety +34

    Code on Github: github.com/neetcode-gh/leetcode/blob/main/28-Implement-strStr.py
    I recommend using the timestamps and watching this at 1.5x Speed, at least the LPS portion, which turned out longer than I expected.

    • @yotubecreators47
      @yotubecreators47 Před 2 lety +2

      no that was perfect for guys like me thank you very much

    • @ary_21
      @ary_21 Před rokem +1

      Why cant we use in built stl function
      String.find(substring)
      To locate the index of string ?

    • @xerOnn35
      @xerOnn35 Před rokem +1

      @@ary_21 because this will only return the first occurence of the substring. Morever, the "substring" function internelly works in O(n) time. So the totall complexity would be O(n^2), where the optimal approch has O(n) time. And that's very bad. And also if you want to count the number of occurences of the substring, the "stl function" approach will definitely give you TLE. :)

    • @ary_21
      @ary_21 Před rokem +1

      @@xerOnn35
      Got it 👍
      Thanks !

  • @Luna-vk9xy
    @Luna-vk9xy Před 2 lety +94

    Thank you for acknowledging how complex this algo is. I thought i was crazy for struggling so much. Finally understand it, somewhat :'). Thanks for making this

    • @xr_c5516
      @xr_c5516 Před rokem +3

      exactly. i came back after leaving this algo and did not understand what I wrote at all and I thought I was just being stupid lol

  • @thakurritesh19
    @thakurritesh19 Před rokem +40

    If someone says they can explain KMP better, they are lying. It doesn't get any better than what you just did. Amazing Neetcode. 🙏

  • @bird5680
    @bird5680 Před 2 lety +89

    0:35 - Yes, I too would describe independently re-discovering a complex search algorithm during an interview as "very very hard"

    • @WoWkiddymage
      @WoWkiddymage Před 2 lety +16

      lmao, as soon as I submitted his first solution (m * n) doing it myself and it exceeded time I realized this wasn't going to be an "easy" problem :') . WTH is this leetcode.

    • @ary_21
      @ary_21 Před rokem +6

      @@WoWkiddymage
      To be honest trying the same problem with rabin karps algorithm is very easy.
      If given the hint "each sliding window can have a unique signature" you can yourself re-discover the algo even if not read of before.
      Kmp , booyre moore , rabin karp are all linear algorithms

    • @Iamfafafel
      @Iamfafafel Před 8 měsíci +4

      Especially considering it took 3 guys to initially discover it!

    • @theprnvanand
      @theprnvanand Před 7 měsíci

      @@WoWkiddymage well I wrote a brute force (mentioned below, which got accepted btw) but the code was so ugly, I knew for sure there exists an optimal solution and here I am.
      bool rotateString(string s, string goal) {
      int n = s.size();
      for(int i=0; i

  • @aditichourasia2990
    @aditichourasia2990 Před rokem +14

    I saw many explanations on kmp algo, but the explanation you provided is the best and the easiest to understand, kudos to you !

  • @weihaichen316
    @weihaichen316 Před 2 lety +17

    I wish this video came around sooner. Was asked a similar question during a Microsoft interview two weeks ago. The interviewer expected me to come up or remember KMP lol. But thank you NC! Please keep up the good works!

  • @zhaovincent8039
    @zhaovincent8039 Před 2 lety +19

    The best online KMP algorithm explanation! Thank you Sir!

  • @TheElementFive
    @TheElementFive Před 2 lety +103

    Please try to make future solution videos in this dual screen format. It’s really helpful to visualize the intuition behind each line of code in real time.

  • @gauravgupta5530
    @gauravgupta5530 Před 2 lety +1

    One of the greatest explanations Neel. It's really very helpful and let me tell you I have seen it more than 4 times and now I know how it works. Thanks, man.

  • @whiplash1512
    @whiplash1512 Před 2 lety +57

    We asked for it in the previous video and you made a video on it, thanks!

    • @AsifIqbalR
      @AsifIqbalR Před 2 lety +6

      Exactly, I literally put a comment on his last video. What a legend

  • @CT-po4xs
    @CT-po4xs Před rokem +1

    This is the best KMP solution I've been seen, very clear, thank you!

  • @frenzyf3939
    @frenzyf3939 Před 2 lety +8

    Thank you for your hard work ! Video is incredibly useful and easy to understand.

  • @Anirudh-cf3oc
    @Anirudh-cf3oc Před rokem

    This is the best explaination video for KMP algorithm!! I find that explaining code parallely is very helpful for this algorithm. Thank you for your efforts!!

  • @brecoldyls
    @brecoldyls Před rokem +4

    At 22:00 I think I really started getting it!
    Thanks Neetcode for the clear explanations as usual.

  • @CEOofTheHood
    @CEOofTheHood Před 2 lety +6

    Thanks Mr.Neet for listening.

  • @raghavddps2
    @raghavddps2 Před rokem +1

    This is one of the best explanations to the KMP algorithm, thank you :)

  • @yiyunsu7791
    @yiyunsu7791 Před 2 lety +2

    That is super helpful. I finally understand this, two days

  • @yuvrajjoshi4822
    @yuvrajjoshi4822 Před 7 měsíci +2

    Beautiful explanation, only the one who understands the logic can explain others with such clarity

  • @adrijachakraborty2316
    @adrijachakraborty2316 Před měsícem

    This is really a great attempt at trying to explain the KMP and somewhat some intuition behind why it works! Really a very complicated and non-intuitive algorithm but brilliantly explained here.

  • @nidhiverma1798
    @nidhiverma1798 Před rokem

    u make it so easy and understandable . ig this is the best video on kmp i came across.

  • @genghisda236
    @genghisda236 Před 9 měsíci +1

    Awesome work, ! thank u for putting in so much effort and thanks to me also for making 1/5th effort to make it to the end of this video. good to see that u covered so many test cases, which made the explanation more clear.

  • @tanishqdadhich8589
    @tanishqdadhich8589 Před 2 lety

    Honestly, This was the best explanation I have found on the internet, and trust me I have watched a hell lot smfhhh

  • @mygosity
    @mygosity Před 2 lety +2

    Thanks NeetCode, it's pretty hard to find a good explanation on the KMP algorithm and you did a great job of explaining it here. Would it be possible for you to cover the Aho Corasick algorithm at some point? I'm finding it difficult to find a good resource explaining that one and having a NeetCode explained version would be a nice follow up to this one as I believe Aho Corasick uses KMP to efficiently find substrings in strings along with Tries.

  • @kamaleshs5324
    @kamaleshs5324 Před 2 lety +2

    This is the first video from NeetCode that I can't seem to understand wow! speaks to the complexity of the algo or maybe I am just mediocre XD

  • @bharghavak
    @bharghavak Před rokem

    It's amazing how stuff like this is actually free. Thanks dude!

  • @archivelib3379
    @archivelib3379 Před rokem +1

    Thank you for this amazing video!
    Finally, I understood this algorithm.

  • @AsifIqbalR
    @AsifIqbalR Před 2 lety +6

    Wow. You listened to the feedback from viewers. Goddamn legend ✌

  • @mexijie3634
    @mexijie3634 Před rokem

    Best kmp explanation i've ever found on youtube!!!

  • @XxBruce5002xX
    @XxBruce5002xX Před 2 lety +5

    Excellent attention to feedback

  • @numberonep5404
    @numberonep5404 Před 2 lety

    Enormous thanks for making this video!

  • @autogenes
    @autogenes Před 2 lety +1

    What a great explanation. Thanks!!!!!!

  • @asifiqbalsekh
    @asifiqbalsekh Před 2 lety +3

    You saying again and again it's tough and really it's. But you make the algorithm very easy by your explanation. Superb work....

  • @abishekbaiju1705
    @abishekbaiju1705 Před rokem

    Best KMP algo explanation ever. Thanks neetcode.

  • @harshbhabar51
    @harshbhabar51 Před 11 měsíci +1

    Finally understood this KMP in my 6years of studies. Theenks.💪🏼

  • @yornadnaps4602
    @yornadnaps4602 Před 9 měsíci

    Clean and precise, thanks @NeetCode

  • @SleepeJobs
    @SleepeJobs Před 2 lety

    Hats off to your effort. 👍🏻

  • @Mihir.Hundiwala
    @Mihir.Hundiwala Před rokem +1

    Very well explained thank you so much

  • @ELMlKO
    @ELMlKO Před 6 měsíci +8

    why do u sound like you're explaining it to me for the fifth time

  • @miketsubasa3611
    @miketsubasa3611 Před 6 měsíci

    Very detailed explanation.Thank you very much

  • @clikiw.8812
    @clikiw.8812 Před 2 lety

    Very helpful, thank you!

  • @krshivraj10
    @krshivraj10 Před 8 měsíci

    Simply beautiful explanation. Very near perfect one.

  • @mhashmi3593
    @mhashmi3593 Před 2 lety +1

    Great work. Keep it up :-)

  • @andriidanylov9453
    @andriidanylov9453 Před 2 měsíci

    Appreciate Your hard work. It was hard. I will need to review again a few times to figure out and remember.

  • @spongebobsquarepants4576
    @spongebobsquarepants4576 Před měsícem

    Great explanation! Thank you so much

  • @viditvaish7317
    @viditvaish7317 Před 9 měsíci

    this is the best video on youtube for this question

  • @LiXiaoZhi
    @LiXiaoZhi Před rokem

    Thanks for the amazing explanation!

  • @Luc1an_
    @Luc1an_ Před 2 lety +3

    Sir pls take questions from the previous week's contest. They were too odd and problem statement were not put up correctly. Thanks 😊

  • @SoniaStalance
    @SoniaStalance Před rokem

    Tysm! I would have never understood this if I tried learning on my own.

  • @nehabhavsar4943
    @nehabhavsar4943 Před rokem

    Thanks Man!Saved mine time❤

  • @Pcx357
    @Pcx357 Před rokem

    Great explanation! 👍

  • @aadityabisaria5427
    @aadityabisaria5427 Před rokem

    this was so helpful!! thank u!!

  • @aayushranjan3675
    @aayushranjan3675 Před rokem

    Best explanation! Thanks so much

  • @flocela
    @flocela Před 8 měsíci

    So totally helpful! Thanks!

  • @TheLemitek
    @TheLemitek Před 2 lety +1

    Good stuff Sir ☺️

  • @sanatanify03
    @sanatanify03 Před 9 měsíci

    best explanation on KMP on yt ❤

  • @KunalKumar-lb7ir
    @KunalKumar-lb7ir Před 7 měsíci

    Best explaination I found for KMP thanks

  • @paulofili4486
    @paulofili4486 Před 2 lety +3

    Thanks for this

  • @chiragbirla5606
    @chiragbirla5606 Před 25 dny

    One of the best explanation out there for this hard hard hard algorithm

  • @user-xc6ez1kj6q
    @user-xc6ez1kj6q Před 6 měsíci

    Awesome explanation!

  • @ameydhimte_c5956
    @ameydhimte_c5956 Před rokem

    Yeah true, that's one of your longest videos but you explained KMP-algorithm very clearly

  • @artventure_by_jasse
    @artventure_by_jasse Před 2 lety

    Great explanation.

  • @DeGoya
    @DeGoya Před rokem

    Could you also cover Rabin Karp's algorithm for the same leetcode problem?

  • @rajankhunt7002
    @rajankhunt7002 Před rokem

    Amazing video and explanation.

  • @roshangeorge97
    @roshangeorge97 Před 11 měsíci +1

    first time in neetcode history* bro made it wild

  • @nklido
    @nklido Před 6 měsíci +1

    @NeetCode Please correct me if I'm wrong, but on 19:12, when you say "that's what the 1 tells us..", i think you meant to circle the 1st and the 2nd "A" in the text and not the 1st and 3rd "A".

  • @namankeshari7332
    @namankeshari7332 Před rokem

    Loved this video!

  • @apputadhiyal9451
    @apputadhiyal9451 Před 2 měsíci

    Thank you for the video.

  • @danielhemmati
    @danielhemmati Před rokem

    this was really helpful thanks

  • @morningstar1913
    @morningstar1913 Před 18 dny

    Great Explanation 🙌🙌🙌🙌

  • @princebillygrahamkarmoker2122
    @princebillygrahamkarmoker2122 Před 11 měsíci

    That just went through my brain. thanks

  • @ankitaverma5542
    @ankitaverma5542 Před 4 měsíci +1

    prevlps is the value stored or the pointer to that location?

  • @jinyang4796
    @jinyang4796 Před 2 lety

    Thank you so much!

  • @_soundwave_
    @_soundwave_ Před 11 měsíci

    I did this yesterday on leetcode. After solving it turnns out to be KMP algorithm.

  • @J1MKAKA1N
    @J1MKAKA1N Před rokem

    Can someone tell the difference between LPS and DFA (Deterministic finite automaton) in the context of the algorithm?

  • @gothien205
    @gothien205 Před 2 lety +3

    I do not understand the tricky part when building the LPS array, when i and j do not match, why move j by the VPS[i - 1]? Because move that way you will skip some middle elements. Is there a proof that garentee the longest prefix suffix?

  • @PerryAgent
    @PerryAgent Před 2 lety +1

    Incredible explanation! Thanks for the video.

  • @genghisda236
    @genghisda236 Před 8 měsíci

    bro i got google screening interview in few days - i remember u said in one of the videos that you can find the screening question online, but i dont see it. although i have prepared from leetcode. But i remember u said the question are easy, it not that easy also, its all good medium level problems

  • @chaithanyachallapalli8608

    cant we use rabin karp algorithm it also takes o(|n| +|m|) right?

  • @paraskumar693
    @paraskumar693 Před 2 lety +2

    If prevLPS come backs to prevLPS=0 then it can further move max n-i steps ,that's why time complexity is O(N)

  • @shiveshgupta1705
    @shiveshgupta1705 Před měsícem

    You always explain such this it is one of the best explanation🤩

  • @satyamgaba
    @satyamgaba Před rokem +1

    I was asked this for FAANG interview

  • @user-et8om7cl2j
    @user-et8om7cl2j Před rokem

    I don't understand why we use prevLps as an index , but set the value from lps[prevLps - 1]; Why value can be used as index?

  • @bhavyagupta3565
    @bhavyagupta3565 Před 3 měsíci

    hey Neetcode at timestamp 22:40, why was LPS[6]!= 6? because for the substring 'AAACAAA' -> prefix(AAACAA)==suffix('AAACAA') and that length is 6. please tell me if i am mistaken.

  • @Saeed-Tanjim
    @Saeed-Tanjim Před rokem

    thanks! it's helpful

  • @ChoweeChubbs
    @ChoweeChubbs Před 10 měsíci

    thank you sir!

  • @gothien205
    @gothien205 Před 2 lety

    I dont understand why prevLPS = lps[prevLPS - 1]? is that always right?

  • @shreyasaini5840
    @shreyasaini5840 Před 6 měsíci

    you are awesome, thank you

  • @opus6630
    @opus6630 Před rokem +1

    Hey guys, I have a question regarding the calculation of the LPS array. When it comes to the "else" condition, why do we let prevLPS = LPS[prevLPS-1] instead of decrementing prevLPS by 1? 🤔 THANKS.

    • @prakhargupta4320
      @prakhargupta4320 Před 11 měsíci

      I was wondering the same thing
      If you found an explanation please share

    • @vijaybenz9741
      @vijaybenz9741 Před 6 měsíci

      @@prakhargupta4320 checj for other strings as well youy will get it

  • @shivamkansagara4929
    @shivamkansagara4929 Před rokem

    thank you very much

  • @mandeepsinghsoorma3080

    very helpful video

  • @user-gh6sz6jn9v
    @user-gh6sz6jn9v Před 2 měsíci

    24:10 I wonder why here we can say LPS[2]'s value means the first two chars match the 5th,6th chars. In my view when the LPS[2] is determined, we don't know the following matches, so its value can only tell the first two match the 1th,2th two (matching prefix-suffix numbers up to current bit). Since then LPS[2] haven't change, why has the meaning changed? Thank you the same.

  • @shreyrawat7108
    @shreyrawat7108 Před 11 měsíci

    Thanks a lot.

  • @shaporovanatalia6805
    @shaporovanatalia6805 Před rokem

    am I correct that these algorithm does not work correct for such case
    string haystack ("ababcaababcaabc");
    string needle ("ababcaabc");

  • @orellavie6233
    @orellavie6233 Před 2 lety

    By the end of the video it looks like if you saved the X, the pointer of the needle would need to go back again. If I am not wrong, worst case is O(n*m) like rabin karp, as if the needle is AAAA and the hays is like AAAX copied many many times, it always will go back to the start of LPS array. Thus, O(n*m)

  • @MrLeyt1125
    @MrLeyt1125 Před 4 měsíci

    Can you do Leetcode 30 video? I wander how can we implement KMP in it

  • @Akmabedinkadersafi-O
    @Akmabedinkadersafi-O Před 6 měsíci

    Best explanation

  • @gamefun2525
    @gamefun2525 Před 3 měsíci

    Tbh if you wrap your head around the working of the KMP algo, it’s not that complicated and pretty astonishing what it achieves

  • @source144
    @source144 Před 2 lety +1

    Not me legitimately saying "wow" when you went dual screen mode 😭

  • @supremoluminary
    @supremoluminary Před rokem

    23:34 “C“ is at index three, not index four; 0, 1, 2, 3…

  • @ishanporwal4403
    @ishanporwal4403 Před rokem

    at 24:28 you said that that we would take lps[prevLPS] and add 1 to it but in the code in first condition you wrote lps[i]=prevLPS+1 and not lps[prevLPS] +1