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

  Рет қаралды 150,590

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Twitter: / neetcode1
Discord: / discord
💡 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/regular-...
Code on Github: github.com/neetcode-gh/leetco...
0:00 - Read the problem
3:55 - Drawing Solution
19:00 - Coding Solution
leetcode 10
This question was identified as a google interview question from here: github.com/xizhengszhang/Leet...
#regular #expression #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 184
@NeetCode
@NeetCode 3 жыл бұрын
Dynamic Programming Playlist: kzbin.info/www/bejne/bWTVZH6Nnqqpr80
@parambole8671
@parambole8671 3 жыл бұрын
If I crack my FB interviews it's only going to be because of this channel. Keep up the "NEET" work :)
@NeetCode
@NeetCode 3 жыл бұрын
Good luck, you're going to do great!
@Avinash_kumar_IITD
@Avinash_kumar_IITD 3 жыл бұрын
same for me, I cracked Microsoft India interview
@_ipsissimus_
@_ipsissimus_ 2 жыл бұрын
Hey boss, what coding problem did they ask you?
@yukselpolatakbyk8468
@yukselpolatakbyk8468 2 жыл бұрын
how did it go??
@RaghavSharma-nt3hr
@RaghavSharma-nt3hr 2 жыл бұрын
did u crack?? 😅
@sudheerk7989
@sudheerk7989 2 жыл бұрын
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 KZbin 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 Жыл бұрын
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!
@dollyvishwakarma2
@dollyvishwakarma2 2 жыл бұрын
OMG, the question looked so tough, but you made it soo easy !! Another awesome explanation. Great fan of your NEET coding style :)
@chinmaym92
@chinmaym92 3 жыл бұрын
I really appreciate how clean your code was and was so easy to understand
@michaeldunlap2693
@michaeldunlap2693 2 жыл бұрын
This is a fabulous and thorough explanation. The decision tree explanation and visual for the asterisk was what did it for me. Thank you!
@auto8ot644
@auto8ot644 2 жыл бұрын
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 Ай бұрын
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
@xinchenyi9878
@xinchenyi9878 3 жыл бұрын
The clearest explanation I've seen!!! You are awesome :)
@buttercup5029
@buttercup5029 2 жыл бұрын
I was struggling a lot with this question. Your video cleared my doubts. Thanks for sharing!
@santoshr4212
@santoshr4212 8 ай бұрын
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
@TheRetrobek
@TheRetrobek 2 жыл бұрын
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 2 жыл бұрын
Ty so much, I was stuck trying to figure out where it was saving time
@80kg
@80kg 2 жыл бұрын
thank you for pointing out the test case it's important for understanding why caching is effective at saving time
@shalsteven
@shalsteven 11 ай бұрын
how did you come with that example to identify the sub-problem?
@arpanbanejee5143
@arpanbanejee5143 2 жыл бұрын
Simply mind-blowing explanation, you made it so simple!! Thanks you! Please keep up the good work!
@hakoHiyo271
@hakoHiyo271 3 жыл бұрын
Great explanation! You explained the algorithm very clearly. I'm not even Python guy, but I still liked your video!
@vdyb745
@vdyb745 2 жыл бұрын
What a brilliant solution and in-depth explanation for this seriously hard problem !!! WOW .... Thank you !!!!
@yukselpolatakbyk8468
@yukselpolatakbyk8468 2 жыл бұрын
You make this question easy to udnerstand. Thank you for all your amazing solutions!!
@user-po5dk2xr7d
@user-po5dk2xr7d Жыл бұрын
This explanation makes the whole process clean and simple.
@pranavkashyap8610
@pranavkashyap8610 Жыл бұрын
The dramatic decrease in time taken to execute after using cache surprised me . Thanks for the explanation and code
@Iamnoone56
@Iamnoone56 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??
@AbanoubAsaad-YT
@AbanoubAsaad-YT 2 жыл бұрын
BEST EXPLANATIONS ARE HERE :) Thank you so much for these quality videos!
@thinja
@thinja 2 жыл бұрын
Wow so much easier to understand than the DP solution! Thanks for showing your mistakes as well
@kanwarkajla
@kanwarkajla 2 жыл бұрын
great explanation .....also the vibe of ur videos is relaxing!
@ruizhu5295
@ruizhu5295 2 жыл бұрын
I really appreciate your explanation, so clean, so logical!
@VishalKumar-kr9me
@VishalKumar-kr9me Жыл бұрын
How easy you make a hard problem is unbelievable !!!!!! Salute to you
@jerryjohnthomas4908
@jerryjohnthomas4908 2 жыл бұрын
can some one explain what happens if i==m and j
@sauravchandra10
@sauravchandra10 10 ай бұрын
You make hard problems very easy. Thanks for explaining.
@eyosiasbitsu4919
@eyosiasbitsu4919 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 жыл бұрын
How do you have an October interview scheduled in May? Full time or internship? Goodluck
@nealp9084
@nealp9084 Ай бұрын
did you pass?
@amitavamozumder73
@amitavamozumder73 3 жыл бұрын
can i do it just by using a stack? push any pattern and if found star removes all stack top char and pop it and move on. in case of .* we just push it in the stack and move on..
@Tyokok
@Tyokok 3 жыл бұрын
Thanks for great explain! Do you also have an explain on complexity analysis of this recursive call? Thank you!
@kaartiknagarajan5009
@kaartiknagarajan5009 Жыл бұрын
I've recoded your solution and it's brilliant. However, I've been trying to follow the stack trace of the program execution to convince myself when the first if statement would execute "if (i, j) in cache: return cache([i, j])". I know it does because I tried removing it and got a TLE error o Leetcode, but I don't see when it would be needed as we always progress into a deeper DFS and cache. Would appreciate an explanation if you could please! Thank you.
@Whatthetrash
@Whatthetrash Жыл бұрын
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.
@shashwatmaru9238
@shashwatmaru9238 3 жыл бұрын
Hey what would be the Time and Space complexity ? Backtracking with memoization means 2^n?
@saadkhan4049
@saadkhan4049 4 ай бұрын
You made it look so simple. Thank you!
@scottchen2094
@scottchen2094 2 жыл бұрын
Can someone explain why we dont add cache for line 11 & line 13 the two base cases?
@comander47
@comander47 Жыл бұрын
this problem took me soo much time to understand, thank you dude
@juliramoos
@juliramoos 4 ай бұрын
Perfect explanation! Thank you. And the code looks good.
@user-or7qq1bz1q
@user-or7qq1bz1q 6 ай бұрын
but I got a doubt how are we looping the string if we ae not using any loop. like it will check all the conditions for 1 time but how is it looping ??? can anyone help?
@yangyue2791
@yangyue2791 3 жыл бұрын
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.
@capriworld
@capriworld 2 жыл бұрын
Best explanation ever found for this problem.
@rahuljain281
@rahuljain281 5 ай бұрын
What an explanation sir ji❤. After this, I was able to solve wildcard matching by myself.
@krugerbrent4270
@krugerbrent4270 2 жыл бұрын
Wow! You made it look like a piece 'o cake. Thanks, I really appreciate it.
@jonathanandres1657
@jonathanandres1657 7 ай бұрын
Great explanation! :) @NeetCode what tool do you use to write and draw ? Any specific brand, I'm looking for this kind of tools
@notsadsisyphus6224
@notsadsisyphus6224 2 жыл бұрын
i seriously love your video i swear you dont waste time i love it
@sunginjung3854
@sunginjung3854 3 жыл бұрын
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.
@daved1113
@daved1113 2 жыл бұрын
Excellent work. Earned a sub. Keep it up.
@MutuallyBro
@MutuallyBro Жыл бұрын
Very good explanation, love the channel!
@NAVNEET549
@NAVNEET549 2 жыл бұрын
Awesome explanation. Thank you so much
@chaoluncai4300
@chaoluncai4300 Жыл бұрын
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
@nishapaila7870
@nishapaila7870 11 күн бұрын
just a clean explanation amazing
@iharshgarg
@iharshgarg 6 ай бұрын
i checked so many videos of this problem.. but there's simply no compedition to you bro. keep the neet work up bro/>
@ashkankipati
@ashkankipati Жыл бұрын
Could you explain wildcard matching, a similar problem to this one?
@Demo-yc8fb
@Demo-yc8fb Жыл бұрын
what if s reaches the end but p does not? That will not always return a true right? Where did we cover that case?
@anonofDeath
@anonofDeath 2 жыл бұрын
Can someone explain to me how the aab == c*a*b? Isn't it suppose to cover the entire string?
@lootlook5148
@lootlook5148 2 жыл бұрын
WTF !! Bro You made clear in just 20 minutes🤩
@Avuvos
@Avuvos 3 жыл бұрын
Great video and explanation thank you!
@z08840
@z08840 3 жыл бұрын
by switching "use" and "don't use" in or return statement you can significantly cut complexity down even without memoization
@sachin_yt
@sachin_yt 2 жыл бұрын
I loved it man, thanks a lot :)
@nagasivakrishna5660
@nagasivakrishna5660 Жыл бұрын
man love ur explanation ,great man ,no words love u man
@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
@pranavsharma7479
@pranavsharma7479 2 жыл бұрын
thnks bro i was not getting how to solve this , this is same as wildcard matching with a twist
@xinniu3145
@xinniu3145 2 жыл бұрын
Thank you! this is owesome!
@emretekmen1602
@emretekmen1602 7 ай бұрын
you need to explain how the cache actually saves time. How does storing the indexes along with a bool value save any time?
@somilsinghai5966
@somilsinghai5966 2 жыл бұрын
This question makes me appreciate the hard work of people who have created the full-blown regex.
@aldogutierrez8240
@aldogutierrez8240 Жыл бұрын
Very good explanation thanks!
@sungiv
@sungiv 2 жыл бұрын
this algorithm is not working for case s="aa" and p="*". since its checking for j+1 for * its not working..
@JameS00989
@JameS00989 Жыл бұрын
Super awesome explanation NeetCode 🎉Thanku
@taroserigano6546
@taroserigano6546 Жыл бұрын
Super thanks for this!
@emmatime2016
@emmatime2016 3 жыл бұрын
Great video!!!! Thank you!
@purnimadas768
@purnimadas768 6 ай бұрын
Thank you for the very good video
@thisissheraf2633
@thisissheraf2633 2 жыл бұрын
Appreciate your explanation thank you
@kocot.
@kocot. Ай бұрын
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.
@Varukimm
@Varukimm 12 күн бұрын
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
@sameerkumar-uq2ic
@sameerkumar-uq2ic 5 ай бұрын
how did he changed the leetcode code editor to this color
@anujdoshi882
@anujdoshi882 2 жыл бұрын
Amazing explanation!
@yongquanrao7398
@yongquanrao7398 3 жыл бұрын
Great one. Thanks.
@sauravchandra10
@sauravchandra10 10 ай бұрын
If there is one thing which I am not sure is how will the subproblems repeat. If anyone has any intuitive way, pls let me know.
@haodantan2014
@haodantan2014 3 жыл бұрын
Best explanations! Thank you!
@NeetCode
@NeetCode 3 жыл бұрын
Thanks 😊
@tanaysingh5348
@tanaysingh5348 10 ай бұрын
the question description feels really incomplete without your explanation , thanks a lot
@MsSkip60
@MsSkip60 3 жыл бұрын
Awesome mate!
@Chirayu19
@Chirayu19 10 ай бұрын
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!
@zl7460
@zl7460 Жыл бұрын
Thank you for the explanation. I thought according to the problem statement, 'c*' cannot be empty, which was very misleading by Leetcode.
@siddharthpandey8516
@siddharthpandey8516 2 жыл бұрын
This was perfect!
@MaxFung
@MaxFung 2 жыл бұрын
thank god for this guy i was STUCK
@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)
@biancafuu
@biancafuu 10 ай бұрын
Does anyone know why does the solution run into max recursion depth problem if I set the condition as : (dfs(i+1, j) and match) or dfs(i, j+2) for the dfs call instead of : dfs(i, j+2) or ((dfs(i+1, j) and match)) (I switch the order of the recursion call) 🤔
@nikosreg9710
@nikosreg9710 Ай бұрын
I think it's because you don't allow short-circuiting evaluation of your logical expressions to take place, saving you from the fact that there will always be one branch in your decision tree that accepts the star (left branch in the diagram in the video), thus leading to an infinite branch. Note: the fact that one branch of the tree can be infinitely extended is not false. That's the notion of "*" anyways. You just should make use of python's short-circuiting to avoid this infinite trap...
@dineshkannam8078
@dineshkannam8078 3 жыл бұрын
You are a legend.
@tanayshah275
@tanayshah275 3 жыл бұрын
great explanation!
@mirshodoripov1035
@mirshodoripov1035 Жыл бұрын
can you solve it using only re module in python?
@letscode1000
@letscode1000 2 жыл бұрын
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 2 жыл бұрын
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*"
@sumeetchawla3545
@sumeetchawla3545 2 жыл бұрын
Amazing explanation .. Really thankful for your great efforts.. :)
@NeetCode
@NeetCode 2 жыл бұрын
Glad it was helpful!
@danielsun1993
@danielsun1993 3 жыл бұрын
The best explanation!!!
@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.
@lingyunsu1589
@lingyunsu1589 2 жыл бұрын
Best explanation ever!
@saikat511
@saikat511 2 жыл бұрын
will it work with s: aaa, p: aab*a*c*a ??
@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.
@MonkeyHitsDonkey
@MonkeyHitsDonkey 2 жыл бұрын
Can someone please explain how the time complexity is improved from O(2^n) to O(m*n) using a cache
@Terracraft321
@Terracraft321 2 жыл бұрын
"Bilguun 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."
@pinkylover911
@pinkylover911 2 жыл бұрын
you are talented
@pulakammalathy6968
@pulakammalathy6968 Жыл бұрын
Thank you so much
@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.
@koppan
@koppan 3 жыл бұрын
Thanks a lot :)
Jump Game - Greedy - Leetcode 55
16:28
NeetCode
Рет қаралды 220 М.
Coin Change - Dynamic Programming Bottom Up - Leetcode 322
19:23
路飞被小孩吓到了#海贼王#路飞
00:41
路飞与唐舞桐
Рет қаралды 76 МЛН
Clowns abuse children#Short #Officer Rabbit #angel
00:51
兔子警官
Рет қаралды 72 МЛН
Regular Expressions (Regex) Tutorial: How to Match Any Pattern of Text
37:55
Fast Inverse Square Root - A Quake III Algorithm
20:08
Nemean
Рет қаралды 5 МЛН
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 351 М.
Median of Two Sorted Arrays - Binary Search - Leetcode 4
22:22
N-Queens - Backtracking - Leetcode 51 - Python
17:51
NeetCode
Рет қаралды 154 М.
Big-O Notation - For Coding Interviews
20:38
NeetCode
Рет қаралды 431 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 140 М.
Network Delay Time - Dijkstra's algorithm - Leetcode 743
19:48
iPhone, Galaxy или Pixel? 😎
0:16
serg1us
Рет қаралды 606 М.
КРУТОЙ ТЕЛЕФОН
0:16
KINO KAIF
Рет қаралды 6 МЛН
1$ vs 500$ ВИРТУАЛЬНАЯ РЕАЛЬНОСТЬ !
23:20
GoldenBurst
Рет қаралды 1,8 МЛН
Как правильно выключать звук на телефоне?
0:17
Люди.Идеи, общественная организация
Рет қаралды 1,7 МЛН