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

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ส.ค. 2024

ความคิดเห็น • 162

  • @NeetCode
    @NeetCode  2 ปีที่แล้ว +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 2 ปีที่แล้ว +2

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

    • @ary_21
      @ary_21 ปีที่แล้ว +1

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

    • @xerOnn35
      @xerOnn35 ปีที่แล้ว +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 ปีที่แล้ว +1

      @@xerOnn35
      Got it 👍
      Thanks !

  • @thakurritesh19
    @thakurritesh19 ปีที่แล้ว +43

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

  • @Luna-vk9xy
    @Luna-vk9xy 2 ปีที่แล้ว +97

    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 ปีที่แล้ว +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

  • @bird5680
    @bird5680 2 ปีที่แล้ว +92

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

    • @WoWkiddymage
      @WoWkiddymage 2 ปีที่แล้ว +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 ปีที่แล้ว +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 9 หลายเดือนก่อน +4

      Especially considering it took 3 guys to initially discover it!

    • @theprnvanand
      @theprnvanand 8 หลายเดือนก่อน

      @@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 2 ปีที่แล้ว +15

    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 2 ปีที่แล้ว +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 2 ปีที่แล้ว +19

    The best online KMP algorithm explanation! Thank you Sir!

  • @TheElementFive
    @TheElementFive 2 ปีที่แล้ว +105

    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.

  • @whiplash1512
    @whiplash1512 2 ปีที่แล้ว +57

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

    • @AsifIqbalR
      @AsifIqbalR 2 ปีที่แล้ว +6

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

  • @yuvrajjoshi4822
    @yuvrajjoshi4822 8 หลายเดือนก่อน +2

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

  • @brecoldyls
    @brecoldyls ปีที่แล้ว +4

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

  • @adrijachakraborty2316
    @adrijachakraborty2316 2 หลายเดือนก่อน

    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.

  • @chiragbirla5606
    @chiragbirla5606 หลายเดือนก่อน +1

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

  • @CEOofTheHood
    @CEOofTheHood 2 ปีที่แล้ว +6

    Thanks Mr.Neet for listening.

  • @ELMlKO
    @ELMlKO 6 หลายเดือนก่อน +11

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

  • @CT-po4xs
    @CT-po4xs ปีที่แล้ว +1

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

  • @gauravgupta5530
    @gauravgupta5530 2 ปีที่แล้ว +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.

  • @AsifIqbalR
    @AsifIqbalR 2 ปีที่แล้ว +6

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

  • @frenzyf3939
    @frenzyf3939 2 ปีที่แล้ว +8

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

  • @Anirudh-cf3oc
    @Anirudh-cf3oc 2 ปีที่แล้ว

    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!!

  • @asifiqbalsekh
    @asifiqbalsekh 2 ปีที่แล้ว +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....

  • @genghisda236
    @genghisda236 10 หลายเดือนก่อน +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.

  • @raghavddps2
    @raghavddps2 ปีที่แล้ว +1

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

  • @harshbhabar51
    @harshbhabar51 ปีที่แล้ว +1

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

  • @XxBruce5002xX
    @XxBruce5002xX 2 ปีที่แล้ว +5

    Excellent attention to feedback

  • @kamaleshs5324
    @kamaleshs5324 2 ปีที่แล้ว +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

  • @tanishqdadhich8589
    @tanishqdadhich8589 2 ปีที่แล้ว

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

  • @nklido
    @nklido 7 หลายเดือนก่อน +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".

  • @bharghavak
    @bharghavak 2 ปีที่แล้ว

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

  • @abishekbaiju1705
    @abishekbaiju1705 ปีที่แล้ว

    Best KMP algo explanation ever. Thanks neetcode.

  • @nidhiverma1798
    @nidhiverma1798 ปีที่แล้ว

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

  • @yiyunsu7791
    @yiyunsu7791 2 ปีที่แล้ว +2

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

  • @archivelib3379
    @archivelib3379 ปีที่แล้ว +1

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

  • @mexijie3634
    @mexijie3634 ปีที่แล้ว

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

  • @viditvaish7317
    @viditvaish7317 10 หลายเดือนก่อน

    this is the best video on youtube for this question

  • @andriidanylov9453
    @andriidanylov9453 3 หลายเดือนก่อน

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

  • @mygosity
    @mygosity 2 ปีที่แล้ว +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.

  • @spongebobsquarepants4576
    @spongebobsquarepants4576 2 หลายเดือนก่อน

    Great explanation! Thank you so much

  • @Luc1an_
    @Luc1an_ 2 ปีที่แล้ว +3

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

  • @ameydhimte_c5956
    @ameydhimte_c5956 ปีที่แล้ว

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

  • @gothien205
    @gothien205 2 ปีที่แล้ว +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?

    • @kirtikhohal5025
      @kirtikhohal5025 2 ปีที่แล้ว +1

      yew, i also want answer for this logic

  • @paraskumar693
    @paraskumar693 2 ปีที่แล้ว +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)

  • @krshivraj10
    @krshivraj10 9 หลายเดือนก่อน

    Simply beautiful explanation. Very near perfect one.

  • @SoniaStalance
    @SoniaStalance ปีที่แล้ว

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

  • @KunalKumar-lb7ir
    @KunalKumar-lb7ir 8 หลายเดือนก่อน

    Best explaination I found for KMP thanks

  • @Mihir.Hundiwala
    @Mihir.Hundiwala 2 ปีที่แล้ว +1

    Very well explained thank you so much

  • @roshangeorge97
    @roshangeorge97 11 หลายเดือนก่อน +1

    first time in neetcode history* bro made it wild

  • @ankitaverma5542
    @ankitaverma5542 5 หลายเดือนก่อน +1

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

  • @miketsubasa3611
    @miketsubasa3611 7 หลายเดือนก่อน

    Very detailed explanation.Thank you very much

  • @RAjat9590
    @RAjat9590 2 ปีที่แล้ว +2

    The problem with this explanation is while building the needle array,
    when we have needle[i] == needle[prevLPS], we set the value,
    lps[i] = prevLPS + 1 but you keep saying we are incrementing the value by 1 of prevLPS index value in lps array whereas we are setting the incremented value of prevLPS and not the index value of it i.e. lps[i] = prevLPS + 1 and NOT lps[i] = lps[prevLPS] + 1
    Coincidentally the examples choosen had the same index value and the value inside lps array i.e. value at index 1 is 1 and value at index 2 is 2 that's why i think the choice of example was poor.
    Other than that the explanation was great.

    • @khushwindersingh2541
      @khushwindersingh2541 7 หลายเดือนก่อน

      I am thinking same, and spent so much time on it tow find out explanation is wrong

  • @yornadnaps4602
    @yornadnaps4602 10 หลายเดือนก่อน

    Clean and precise, thanks @NeetCode

  • @shiveshgupta1705
    @shiveshgupta1705 2 หลายเดือนก่อน

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

  • @sanatanify03
    @sanatanify03 10 หลายเดือนก่อน

    best explanation on KMP on yt ❤

  • @paulofili4486
    @paulofili4486 2 ปีที่แล้ว +3

    Thanks for this

  • @bhavyagupta3565
    @bhavyagupta3565 4 หลายเดือนก่อน

    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.

  • @opus6630
    @opus6630 ปีที่แล้ว +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 ปีที่แล้ว

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

    • @vijaybenz9741
      @vijaybenz9741 7 หลายเดือนก่อน

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

  • @autogenes
    @autogenes 2 ปีที่แล้ว +1

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

  • @morningstar1913
    @morningstar1913 หลายเดือนก่อน

    Great Explanation 🙌🙌🙌🙌

  • @LiXiaoZhi
    @LiXiaoZhi ปีที่แล้ว

    Thanks for the amazing explanation!

  • @numberonep5404
    @numberonep5404 2 ปีที่แล้ว

    Enormous thanks for making this video!

  • @user-gh6sz6jn9v
    @user-gh6sz6jn9v 3 หลายเดือนก่อน

    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.

  • @satyamgaba
    @satyamgaba ปีที่แล้ว +1

    I was asked this for FAANG interview

  • @apputadhiyal9451
    @apputadhiyal9451 3 หลายเดือนก่อน

    Thank you for the video.

  • @TheLemitek
    @TheLemitek 2 ปีที่แล้ว +1

    Good stuff Sir ☺️

  • @aayushranjan3675
    @aayushranjan3675 ปีที่แล้ว

    Best explanation! Thanks so much

  • @SleepeJobs
    @SleepeJobs 2 ปีที่แล้ว

    Hats off to your effort. 👍🏻

  • @user-xc6ez1kj6q
    @user-xc6ez1kj6q 7 หลายเดือนก่อน

    Awesome explanation!

  • @flocela
    @flocela 9 หลายเดือนก่อน

    So totally helpful! Thanks!

  • @eshikarya
    @eshikarya 9 วันที่ผ่านมา

    Hi! I'm still relatively new to DSA so would appreciate if anyone can guide me with my question?
    I am confused as to why we need to work with KMP algorithm when we can directly use the indexOf() method to check if pattern exists in the String.
    I agree and understand that indexOf() itself might have some underlying algorithm that gets the work done for us.
    Do we learn this for scenarios where we can't use pre-defined methods and need to write our own code?

  • @nehabhavsar4943
    @nehabhavsar4943 ปีที่แล้ว

    Thanks Man!Saved mine time❤

  • @gamefun2525
    @gamefun2525 4 หลายเดือนก่อน

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

  • @Pcx357
    @Pcx357 ปีที่แล้ว

    Great explanation! 👍

  • @rajankhunt7002
    @rajankhunt7002 ปีที่แล้ว

    Amazing video and explanation.

  • @roboter8666
    @roboter8666 4 หลายเดือนก่อน +1

    I was like after checking out what others solutions made by other users beats mine after I just spent my whole day learning this algorithm, and guess what? THIS:
    class Solution:
    def strStr(self,haystack: str,needle:str)->int:
    if needle in haystack:
    return haystack.index(needle)
    else:
    return-1

    • @Mystic998
      @Mystic998 2 หลายเดือนก่อน

      Probably because list.index implements this algorithm (or similar) but in C rather than Python.
      Side note: Since list.index throws a ValueError if the substring isn't found, it's probably better to do this as a try-except block rather than checking if the substring exists then finding it.

  • @princebillygrahamkarmoker2122
    @princebillygrahamkarmoker2122 ปีที่แล้ว

    That just went through my brain. thanks

  • @_soundwave_
    @_soundwave_ 11 หลายเดือนก่อน

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

  • @a.m.4154
    @a.m.4154 4 หลายเดือนก่อน

    If you think KMP is complicated, try Boyer-Moore using both shift-value table and good-suffix rule.

  • @vasujhawar.6987
    @vasujhawar.6987 ปีที่แล้ว

    Thank you so much!

  • @gothien205
    @gothien205 2 ปีที่แล้ว

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

  • @chaithanyachallapalli8608
    @chaithanyachallapalli8608 ปีที่แล้ว

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

  • @ivanzhovannik5419
    @ivanzhovannik5419 2 ปีที่แล้ว +1

    Now I finally understood why all my Computer Science peers in uni always told me "Knuth's algos are pure SUFFERING" XD Thanks for this very nice explanation, man! Like :+1:

  • @aadityabisaria5427
    @aadityabisaria5427 ปีที่แล้ว

    this was so helpful!! thank u!!

  • @artventure_by_jasse
    @artventure_by_jasse 2 ปีที่แล้ว

    Great explanation.

  • @clikiw.8812
    @clikiw.8812 2 ปีที่แล้ว

    Very helpful, thank you!

  • @source144
    @source144 2 ปีที่แล้ว +1

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

  • @mhashmi3593
    @mhashmi3593 2 ปีที่แล้ว +1

    Great work. Keep it up :-)

  • @stat_life
    @stat_life 9 หลายเดือนก่อน

    I love the audacity of Leetcode to post this question as "EASY"

  • @namankeshari7332
    @namankeshari7332 ปีที่แล้ว

    Loved this video!

  • @danielhemmati
    @danielhemmati 2 ปีที่แล้ว

    this was really helpful thanks

  • @PerryAgent
    @PerryAgent 2 ปีที่แล้ว +1

    Incredible explanation! Thanks for the video.

  • @user-et8om7cl2j
    @user-et8om7cl2j ปีที่แล้ว

    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?

  • @shreyasaini5840
    @shreyasaini5840 7 หลายเดือนก่อน

    you are awesome, thank you

  • @shivamkansagara4929
    @shivamkansagara4929 ปีที่แล้ว

    thank you very much

  • @shaporovanatalia6805
    @shaporovanatalia6805 ปีที่แล้ว

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

  • @supremoluminary
    @supremoluminary ปีที่แล้ว

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

  • @shreyrawat7108
    @shreyrawat7108 ปีที่แล้ว

    Thanks a lot.

  • @Akmabedinkadersafi-O
    @Akmabedinkadersafi-O 7 หลายเดือนก่อน

    Best explanation

  • @itspete2444
    @itspete2444 5 หลายเดือนก่อน

    KMP is great for falling asleep to

  • @ishanporwal4403
    @ishanporwal4403 ปีที่แล้ว

    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

  • @genghisda236
    @genghisda236 9 หลายเดือนก่อน

    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