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

Поделиться
HTML-код
  • Опубликовано: 27 янв 2025

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

  • @NeetCode
    @NeetCode  3 года назад +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 2 года назад +1

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

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

      @@xerOnn35
      Got it 👍
      Thanks !

  • @Luna-vk9xy
    @Luna-vk9xy 2 года назад +141

    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

    • @garvitgarg9455
      @garvitgarg9455 4 месяца назад +2

      Learn same algo from Abdul Bari video on youtube. You will understand it in first attempt

  • @bird5680
    @bird5680 3 года назад +125

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

    • @WoWkiddymage
      @WoWkiddymage 2 года назад +17

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

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

    • @paul_tee
      @paul_tee Год назад +6

      Especially considering it took 3 guys to initially discover it!

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

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

    • @imerence6290
      @imerence6290 6 дней назад

      Yes but I was instead able to come up with Rabin-Karp algorithm instead lol. Well the initial intuition actually.

  • @aditichourasia2990
    @aditichourasia2990 2 года назад +17

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

  • @thakurritesh19
    @thakurritesh19 2 года назад +60

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

    • @ashishdhiwar6226
      @ashishdhiwar6226 Месяц назад +2

      lmao.. this guy says this algo is complex.. just watch abdul bari's video on KMP. He has explained it in a much better and easier way

  • @weihaichen316
    @weihaichen316 3 года назад +19

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

    The best online KMP algorithm explanation! Thank you Sir!

  • @whiplash1512
    @whiplash1512 3 года назад +62

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

    • @AsifIqbalR
      @AsifIqbalR 3 года назад +6

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

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

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

  • @TheElementFive
    @TheElementFive 3 года назад +113

    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.

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

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

  • @ELMlKO
    @ELMlKO Год назад +47

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

  • @junnunsafoan3977
    @junnunsafoan3977 2 месяца назад +1

    I don't usually watch RUclips videos for LC, but KMP had my brain on buffer. Your example walkthrough just made it click for me. Very Neet solution.

  • @itspete2444
    @itspete2444 10 месяцев назад +7

    KMP is great for falling asleep to

  • @frenzyf3939
    @frenzyf3939 2 года назад +9

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

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

  • @CT-po4xs
    @CT-po4xs 2 года назад +1

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

  • @CEOofTheHood
    @CEOofTheHood 3 года назад +6

    Thanks Mr.Neet for listening.

  • @kamaleshs5324
    @kamaleshs5324 3 года назад +4

    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

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

    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.

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

  • @AsifIqbalR
    @AsifIqbalR 3 года назад +6

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

  • @genghisda236
    @genghisda236 Год назад +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.

  • @saurabhbhagat4528
    @saurabhbhagat4528 2 месяца назад +1

    For people wondering like me whether the LPS computation is the same as Z-function of a string...
    It's conceptually similar, but not the same, a simple explanation would be, that LPS matches the prefix of s with the suffix "ending" at position i, while Z-function matches the prefix of s with the substring starting "from" i.

  • @chiragbirla5606
    @chiragbirla5606 6 месяцев назад +1

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

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

    Excellent attention to feedback

  • @ankitaverma5542
    @ankitaverma5542 10 месяцев назад +1

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

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

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

    Thanks a ton man! I've watched a lot of videos on kmp but I found your explanation super easy.

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

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

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

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

  • @Abhinav-eu5le
    @Abhinav-eu5le Год назад

    The explanation of lps array is bit confusing in the above video,
    better explanation can be found here -> ruclips.net/video/ziteu2FpYsA/видео.html

  • @AbinashPanigrahi011
    @AbinashPanigrahi011 4 месяца назад +1

    Great explanation. Finally understood LPS.

  • @syamsreemanojreddy1027
    @syamsreemanojreddy1027 21 день назад

    Thank you so much for your efforts. I have understood the logic behind KMP intuitively🤟

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

    The best explanation yet, thank you. I stumbled across some Indian guys and they explained to me that they know how it works 😢

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

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

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

  • @LyashenkoYegor
    @LyashenkoYegor 18 дней назад

    Thanks

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

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

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

    Best KMP algo explanation ever. Thanks neetcode.

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

    this is the best video on youtube for this question

  • @BirdyObiWan
    @BirdyObiWan 3 месяца назад +1

    The part of constructing lps can be simplified a little. This is from 214. Shortest Palindrome question.
    def prefix_table(self, s):
    lps = [0] * len(s)
    prevLPS = 0
    for i in range(1, len(s)):
    while prevLPS > 0 and s[i] != s[prevLPS]:
    prevLPS = lps[prevLPS - 1]
    if s[i] == s[prevLPS]:
    prevLPS += 1
    lps[i] = prevLPS
    return lps

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

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

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

    Now is 1:21, I am a embedded dev and I don't even use this much algorithm but YT suggest me this bro and now I am here :)). God damn this is so hook, you nailed it so much better than my professor back in the day.

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

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

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

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

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

    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.

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

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

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

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

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

    I‘ve watched this onve before i started studing out of curiosity and now watch it again because i need it

  • @firstjm9071
    @firstjm9071 20 дней назад

    I found it so hard to understand the inner else block. But it clicked for me after 24:00 when you explained what the value 2 meant which was pointed to by p

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

    best explanation on KMP on yt ❤

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

    Simply beautiful explanation. Very near perfect one.

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

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

  • @bhavyagupta3565
    @bhavyagupta3565 10 месяцев назад

    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.

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

    Great Explanation 🙌🙌🙌🙌

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

    Thank you for your excellent explanation ❤

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

    at 19:15, i thing it's wrong or miscommunication because prefix[1] = 1, means pat[0] = pat[1], it does not means pat[0] = pat[2], and it is being said there. Please someone clarify.

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

    You're wrong, with ur explanation, the KMP approach remained easy. Literally I can visualise the pointer iteration in my mind. Kudos @NeetCode
    One more point I would like to add,
    While filling the LPS (Longest Prefix Suffix) array, we essentially filled the length of the valid substring (which matches with LFS criteria).
    But when we're gonna use it in the KMP algorithm part, we treat the array values as indexes, specifically the index in the needle where we'll start matching with the haystack index.
    How we know we can skip the indexes from 0 to index - 1?
    Because of this check haystack [i] == needle [j] and we increased both I and j.
    P.S : We calculated the LPS array independently, with no knowledge about the haystack string.
    Hope it helps!

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

    Clean and precise, thanks @NeetCode

  • @WangshengJi
    @WangshengJi 9 месяцев назад

    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.

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

    the simplest explanation ❤‍🔥❤‍🔥

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

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

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

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

  • @KunalKumar-lb7ir
    @KunalKumar-lb7ir Год назад

    Best explaination I found for KMP thanks

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

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

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

    Time complexity explained (intuition) : 24:50

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

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

  • @tyranitar87
    @tyranitar87 6 дней назад

    At 23:44 there is a small error: you say that prevLPS is 4, but actually is 3, because the array starts from 0

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

    Hats off to your effort. 👍🏻

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

    Good stuff Sir ☺️

  • @Mihir.Hundiwala
    @Mihir.Hundiwala 2 года назад +1

    Very well explained thank you so much

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

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

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

    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?

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

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

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

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

    first time in neetcode history* bro made it wild

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

    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

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

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

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

    Very detailed explanation.Thank you very much

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

    Thanks Man!Saved mine time❤

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

    Great explanation! Thank you so much

  • @1234fewgfwe
    @1234fewgfwe 24 дня назад +1

    after watching for 35 mins, i decided to just memorise it :D call me a god

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

    Great explanation! 👍

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

    Hi I have a question in the code when needle[i] == needle[preLps], you add lps[i] = preLps + 1, but in the vedio you said that you add the lps value. so why you add index in the code but it works?

  • @poptart007-b2r
    @poptart007-b2r 2 года назад

    Enormous thanks for making this video!

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

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

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

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

    I was asked this for FAANG interview

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

    Thanks for the amazing explanation!

  • @ВераЮрьева-м5ш
    @ВераЮрьева-м5ш Год назад

    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?

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

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

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

    Thanks for this

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

    Best explanation! Thanks so much

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

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

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

    So totally helpful! Thanks!

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

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

  • @bhaveshkalra5761
    @bhaveshkalra5761 20 дней назад

    Good explanation !

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

    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

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

    this was so helpful!! thank u!!