Regular Expression Matching - Dynamic Programming Top-Down Memoization - Leetcode 10

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

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

  • @NeetCode
    @NeetCode  3 ปีที่แล้ว +7

    Dynamic Programming Playlist: th-cam.com/video/73r3KWiEvyk/w-d-xo.html

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

    I can't thank enough for this video! Even after spending nearly 3 hours on various videos showing direct DP (bottom-up) solution, and countless posts in Discuss section with no clear explanation, I could not understand how the formulae are derived. But.... this is gem of a video and probably the only video on TH-cam explaining the Top-Down approach.
    In fact, it is better to try Top-Down approach in interviews. Directly trying to attack a problem with DP formula can lead to disasters. If the interviewer is not dumb expecting a specific answer involving DP, he/she/they should be okay with Top-Down+Memoization approach.
    Thanks again! Keep making such amazing videos.

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

    To be honest, I never would have even guessed that this is a Dynamic Programming problem. Once you started explaining the decision tree, it ALL made sense. Thanks for teaching me something new!

  • @parambole8671
    @parambole8671 3 ปีที่แล้ว +175

    If I crack my FB interviews it's only going to be because of this channel. Keep up the "NEET" work :)

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +23

      Good luck, you're going to do great!

    • @Avinash_kumar_IITD
      @Avinash_kumar_IITD 3 ปีที่แล้ว +24

      same for me, I cracked Microsoft India interview

    • @_ipsissimus_
      @_ipsissimus_ 3 ปีที่แล้ว

      Hey boss, what coding problem did they ask you?

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

      how did it go??

    • @RaghavSharma-nt3hr
      @RaghavSharma-nt3hr 2 ปีที่แล้ว +2

      did u crack??
      😅

  • @TheRetrobek
    @TheRetrobek 3 ปีที่แล้ว +30

    If someone didn't get the cache part, try printing out the (i, j) pairs with the following example: text="aaabaaa" and pattern = "a*b*a*".
    If you take a careful look, since we are backtracking, there are cases where we check the same (i, j) pairs. And that's why caching helps.

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

      Ty so much, I was stuck trying to figure out where it was saving time

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

      thank you for pointing out the test case it's important for understanding why caching is effective at saving time

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

      how did you come with that example to identify the sub-problem?

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

      Thanks this is very helpful

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

    Great explanation! I really like how you easily added memoization to the brute force algorithm. Other DP solutions were SO complicated. This explanation was perfect.

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

      Maybe its just me but I found the drawing explanation very confusing although the code made more sense. Usually I love all of Neetcode’s explanations but the pointer usage threw me off around first. There’s a similar problem Wildcard Matching and I solved it by checking the current j index and not j+1, thats why the j+2 was confusing. But in the end the code is very similar.
      I recommend others to try the Wildcard Matching problem its Leetcode 40 or 41

  • @chinmaym92
    @chinmaym92 3 ปีที่แล้ว +5

    I really appreciate how clean your code was and was so easy to understand

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

    OMG, the question looked so tough, but you made it soo easy !! Another awesome explanation. Great fan of your NEET coding style :)

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

    2 more observations/ optimized caches: 1. If j+1 is * and both of its dfs() returned false, we actually dont need to re-check the matching condition again since j+1 is a *, means dfs(i+1, j+1) will fo sho return false due to s[i+1] != p[j+1] which is a *. That being said, we can change the last if (match) condition to else if condition~ 2. current cache will only does its job while next state's dfs() returned false (any next state is true indicates a solution is found). By storing only false returned val into cache will reduce memory space Both opts are negligible / pretty insignificant since either of them only saved limited constant time/space

  • @emretekmen1602
    @emretekmen1602 10 หลายเดือนก่อน +4

    you need to explain how the cache actually saves time. How does storing the indexes along with a bool value save any time?

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

    if this is the case below then :
    '*' Matches any sequence of characters (including the empty sequence).
    def isMatch(self, s: str, p: str) -> bool:
    # top down memo
    cache = {}
    def dfs(i, j):
    if(i, j) in cache:
    return cache[(i, j)]
    if i >= len(s) and j >= len(p):
    return True
    if j >= len(p):
    return False
    if p[j] == '*':
    # Check if the '*' matches an empty sequence or matches one or more characters
    cache[(i, j)] = dfs(i, j + 1) or (i < len(s) and dfs(i + 1, j))
    return cache[(i, j)]
    match = i < len(s) and (s[i] == p[j] or p[j] == "?")
    if match:
    cache[(i, j)] = dfs(i + 1, j + 1)
    return cache[(i, j)]
    cache[(i, j)] = False
    return False
    return dfs(0, 0)

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

    I'll have my google interview in October and this channel is really helping me in my preparation. if i pass then i'll be your biggest supporter neet!

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

      How do you have an October interview scheduled in May? Full time or internship? Goodluck

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

      did you pass?

  • @xinchenyi9878
    @xinchenyi9878 3 ปีที่แล้ว +5

    The clearest explanation I've seen!!! You are awesome :)

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

    Thanks alot for helping me understand the issue, I was doing the bottom up and solution was failing in leetcode on last 2 test cases. After watching this video I understood we need to do bound check on index "i" - stupid of me missing such a basic thing. Now solution worked

  • @hakoHiyo271
    @hakoHiyo271 3 ปีที่แล้ว +6

    Great explanation! You explained the algorithm very clearly. I'm not even Python guy, but I still liked your video!

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

    Simply mind-blowing explanation, you made it so simple!! Thanks you! Please keep up the good work!

  • @袁丽君-s7c
    @袁丽君-s7c 2 ปีที่แล้ว

    This explanation makes the whole process clean and simple.

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

    The dramatic decrease in time taken to execute after using cache surprised me .
    Thanks for the explanation and code

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

    This is a fabulous and thorough explanation. The decision tree explanation and visual for the asterisk was what did it for me. Thank you!

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

    great explanation .....also the vibe of ur videos is relaxing!

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

    Instead of optimizing it with cache, I've got an almost identical result (1300ms->50ms) by simply ensuring you don't process subsequent stars. So if there is a*a*a*, you'd only check it once. Now the cache seems obvious, but that addressed directly the most compute intensive cases :) Funny to see how it's same efficient. Using both would probably improve it even further.

  • @VishalKumar-kr9me
    @VishalKumar-kr9me ปีที่แล้ว

    How easy you make a hard problem is unbelievable !!!!!! Salute to you

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

    I was struggling a lot with this question. Your video cleared my doubts. Thanks for sharing!

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

    Thank you so much for this. After weeks (!) of trying to solve this problem on my own, I decided to look it up and lo and behold -- the solution involves a bunch of stuff that I have never heard of. I feel a bit better (and I need to learn about Dynamic Programming now). >_< Thanks again for the elegant, succinct solution.

  • @jacques-dev
    @jacques-dev ปีที่แล้ว

    For anyone getting confused with the solution to this problem, I found the bottom-up approach to be much more intuitive. Just my experience, I know everyone is different.

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

    Thank you, Neet! Great Explanation!

  • @AbanoubAsaad-YT
    @AbanoubAsaad-YT 2 ปีที่แล้ว

    BEST EXPLANATIONS ARE HERE :)
    Thank you so much for these quality videos!

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

    Wow man your explanation is just fantastic!

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

    You make hard problems very easy. Thanks for explaining.

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

    What a brilliant solution and in-depth explanation for this seriously hard problem !!! WOW .... Thank you !!!!

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

    this problem took me soo much time to understand, thank you dude

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

    I struggled with this problem today without PD. In your example a = a*b* should give true because we use a and a* and remain with 0 b. Correct would be a = a*b

  • @thinja
    @thinja 3 ปีที่แล้ว

    Wow so much easier to understand than the DP solution! Thanks for showing your mistakes as well

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

    i seriously love your video i swear you dont waste time i love it

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

    Thanks Hokage for explaining it really well.Seen a lot of videos where people directly start drawing table.Will memoized soln be enough for an interview or do we have to give a bottom up soln too??

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

    You made it look so simple. Thank you!

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

    you forgot to emphasize during the drawing segment that the reason why it was ok for string p to not match string s, where s = aab and p = c*a*b was becuz the asterik allows c to occur 0 times, its not like what counts as true is if all of the characters in string s are able to be accounted for by stuff in string p, while strickly going left to right through the strings and never backtracking

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

    You make this question easy to udnerstand. Thank you for all your amazing solutions!!

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

    WTF !! Bro
    You made clear in just 20 minutes🤩

  • @木漏れ日-v9n
    @木漏れ日-v9n 7 วันที่ผ่านมา

    The base case can be simplified with
    if j == n:
    return i == m

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

    Yeah, that problem is so hard. I tried to use loops to compare character by character, and deal with * differently. Though, that way did not work well.

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

    the question description feels really incomplete without your explanation , thanks a lot

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

    just a clean explanation amazing

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

    I really appreciate your explanation, so clean, so logical!

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

    Perfect explanation! Thank you. And the code looks good.

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

    What an explanation sir ji❤. After this, I was able to solve wildcard matching by myself.

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

    Hi NeetCode, not sure if LeetCode has added some new test cases, but seems like both top down and bottom up approaches are experiencing TLE for test case s = "aaaaaaaaaaaaaaaaaaab", p = "a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*". Other than that, thanks for your great explanation!

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

    A correction:
    if j>=len(p): return i >= len(s) # If pattern is exhausted, return True only if string is also exhausted

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

    This question makes me appreciate the hard work of people who have created the full-blown regex.

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

    Thank you for the explanation. I thought according to the problem statement, 'c*' cannot be empty, which was very misleading by Leetcode.

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

    man love ur explanation ,great man ,no words love u man

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

    Very good explanation, love the channel!

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

    i checked so many videos of this problem.. but there's simply no compedition to you bro. keep the neet work up bro/>

  • @capriworld
    @capriworld 3 ปีที่แล้ว

    Best explanation ever found for this problem.

  • @z08840
    @z08840 3 ปีที่แล้ว

    by switching "use" and "don't use" in or return statement you can significantly cut complexity down even without memoization

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

    I think the time complexity would be O(N^2M) and not O(N*M) since we have to iterate through the s in case of "*". Please do correct me if I am wrong. Thanks!

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

    Wow! You made it look like a piece 'o cake. Thanks, I really appreciate it.

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

    Excellent work. Earned a sub. Keep it up.

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

    thnks bro i was not getting how to solve this , this is same as wildcard matching with a twist

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

    I have a question, why the testcase - s="a", p=".*..a*" has to return false?
    I mean we just make ".*.." a 0 character string "" and the rest we make one "a".
    Edit: Nevermind I thought '.' can be a 0 character string since in the question it doesn't say anything about it.

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

    Great explanation! :) @NeetCode what tool do you use to write and draw ?
    Any specific brand, I'm looking for this kind of tools

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

    Thanks. its a pretty difficult problem.

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

    Super awesome explanation NeetCode 🎉Thanku

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

    Great video! During your explanation of the examples I had one question, why does "a.." != "aa" if the character "." can represent zero or more of any character? I was thinking that the first period could be "a" and the second period can be empty therefore making aa = aa. Did I understand incorrectly?

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

      Periods must represent a character, they can't be an empty string, only the star can be an empty string.

  • @yangyue2791
    @yangyue2791 3 ปีที่แล้ว

    Would you like to explain the case like "s=aab p=a*ab"? In case like that, we need to take care how much times * copies its preceding letter.

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

    Very good explanation thanks!

  • @python-developer521
    @python-developer521 2 หลายเดือนก่อน

    leet code accepting if 6th line change to j>len(p) instead of j>=len(p)

  • @saksham.malhotra
    @saksham.malhotra 2 ปีที่แล้ว +2

    Thanks!

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

      Thank you so much!

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

    can some one explain what happens if i==m and j

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

    Awesome explanation. Thank you so much

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

    Thank you! this is owesome!

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

    Appreciate your explanation thank you

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

    thank god for this guy i was STUCK

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

    I loved it man, thanks a lot :)

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

    Super thanks for this!

  • @Avuvos
    @Avuvos 3 ปีที่แล้ว

    Great video and explanation thank you!

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

    Thank you for the great video! Is there any chance you could also solve Minimum Difficulty of a Job Schedule (LC 1335)? I would really appreciate it.

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

    You are a legend.

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

    Amazing explanation!

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

    Best explanation ever!

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

    I still don't get how cache helps us... Where is the backtrack step that would benefit from the use of a cache? Don't we use the indices' pair (i, j) only once and then move to the next character?🤔

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

    Amazing explanation .. Really thankful for your great efforts.. :)

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

      Glad it was helpful!

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

    Thank you for the very good video

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

    Your solution may give incorrect answer for some examples for eg.
    If s='aabbddefgh' and p='.*efgh' . In this case your solution will return False. i.e string does not match the pattern because of bounding condition of i and j that you have applied.But in actually the string does matches the regular expression.

  • @emmatime2016
    @emmatime2016 3 ปีที่แล้ว

    Great video!!!! Thank you!

  • @haodantan2014
    @haodantan2014 3 ปีที่แล้ว

    Best explanations! Thank you!

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว

      Thanks 😊

  • @divijjain4674
    @divijjain4674 3 ปีที่แล้ว

    This was the best explanation ever, but I have a doubt. At 18:45 you said its no problem if i is out of bounds and j isn't. But what if for a string S = a, the pattern is P = a*b. In this case, they do not match? Thanks in advance! Really appreciate it.

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

      Yes you're right that those strings don't match, but the function will continue I think and eventually return false in that case.
      For example, in P, there is a remaining b, but the function doesn't yet know if that is a mandatory b, or if it's a b*, because b* means that the b is not mandatory.

    • @divijjain4674
      @divijjain4674 3 ปีที่แล้ว

      @@NeetCode thanks bud got it

  • @danielsun1993
    @danielsun1993 3 ปีที่แล้ว

    The best explanation!!!

  • @Tyokok
    @Tyokok 3 ปีที่แล้ว

    Thanks for great explain! Do you also have an explain on complexity analysis of this recursive call? Thank you!

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

    Could anyone explain how the cache works, I understand the top-down, but don't understand memo as you said, it works well as memo, but when I trace the recursion, cannot see how the cache works?

    • @TheRetrobek
      @TheRetrobek 3 ปีที่แล้ว

      Since we are backtracking, our explorations have a chance of repeating the same (i, j). Try printing out the (i, j) pairs with example as: text="cccbccc" and pattern = "c*b*c*"

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

    I tried your method.
    Did in C++, both recurssion and memoization but there was no big significant difference in the time. Gap was only 20ms. But there is huge time difference in your code. Hows that possible

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

    Excellent tutorial !!!
    In case of P[ j + 1] = '*', why don't we check dfs(i, j+2) only when there is no match. IOW, why don't we do this :
    if (!match) {
    dfs(i , j+2)
    } else {
    dfs(i + 1, j)
    }
    why do we have to do: dfs(i, j + 2) even in case of a match?

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

      Because it can be faster... in that,
      Consider 'a*a*a*aaa' match 'aaa',
      if we check dfs(i, j+2) even in case of current position match 'a' == 'a',
      the pattern would quickly skip all 'a*' cases, match the string with the tailing 'aaa' pattern,
      and return True whatsoever result returned from the other 'matched' side,
      because of the shortcut feature of OR operator.
      And in fact, on the 'matched' side,
      because a* would devour all matched letter 'a' and goes to the very end of the string '' ,
      only to find '' is not matched and return False.
      So if you don't check dfs(i, j+2) before matched side is finished with a False,
      the OR expression have to wait for the other dfs(i, j+2) side result to determine the final boolean value.
      True || (whatsoever) vs False || True, obviously the former is faster.
      Just my opinion.

    • @80kg
      @80kg 2 ปีที่แล้ว

      Aren't those two ways are same? and Wei Wang's explanation only can help with his example. In the case of "bc" "a*a*bc", it jump over to j + 2 because of not matched.

  • @siddharthpandey8516
    @siddharthpandey8516 3 ปีที่แล้ว

    This was perfect!

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

    Does this code cover TC where pattern ends with .* , like s="aab" p="aaa*.*" Iam getting false for such .* Ending cases where I need to ommit * but code returns false as we have passed s length

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

    you are talented

  • @KhoaNguyen-bu7ri
    @KhoaNguyen-bu7ri 2 ปีที่แล้ว

    I don’t know if it’s too much to ask but can you also provide solution in Java 😅. Really love your videos but just can’t keep up with Python. Thanks!

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

    Hey what would be the Time and Space complexity ? Backtracking with memoization means 2^n?

  • @axay3.0
    @axay3.0 ปีที่แล้ว

    this is called Codeagasm. Mind blowing.

  • @yongquanrao7398
    @yongquanrao7398 3 ปีที่แล้ว

    Great one. Thanks.

  • @MsSkip60
    @MsSkip60 3 ปีที่แล้ว

    Awesome mate!