Тёмный

Valid Parenthesis String - Leetcode 678 - Python 

Подписаться
Просмотров 71 тыс.
% 1 392

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: discord.gg/ddjKRXPqtk
🐦 Twitter: neetcode1
🐮 Support the channel: www.patreon.com/NEETcode
⭐ BLIND-75 PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-KLlXCFG5TnA.html
💡 CODING SOLUTIONS: ru-vid.com/group/PLot-Xpze53leF0FeHz2X0aG3zd0mr1AW_
💡 DYNAMIC PROGRAMMING PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-73r3KWiEvyk.html
🌲 TREE PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-OnSn2XEQ4MY.html
💡 GRAPH PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-EgI5nU9etnU.html
💡 BACKTRACKING PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-pfiQ_PS1g8E.html
💡 LINKED LIST PLAYLIST: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-G0_I-ZF0S38.html
💡 BINARY SEARCH PLAYLIST: ru-vid.com/group/PLot-Xpze53leNZQd0iINpD-MAhMOMzWvO
📚 STACK PLAYLIST: ru-vid.com/group/PLot-Xpze53lfxD6l5pAGvCD4nPvWKU8Qo
Python Code: github.com/neetcode-gh/leetcode/blob/main/678-Valid-Parenthesis-String.py
Problem Link: neetcode.io/problems/valid-parenthesis-string
0:00 - Read the problem
2:40 - Drawing Explanation
11:22 - Coding Explanation
leetcode 678
This question was identified as an interview question from here: github.com/xizhengszhang/Leetcode_company_frequency
#facebook #interview #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Наука

Опубликовано:

 

29 янв 2022

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 97   
@NeetCode
@NeetCode 2 года назад
Python Code: github.com/neetcode-gh/leetcode/blob/main/678-Valid-Parenthesis-String.py
@kyu883
@kyu883 2 года назад
i almost committed a crime trying to solve this problem by myself thanks for helping me not become a felon
@pavanpenugonda4924
@pavanpenugonda4924 6 месяцев назад
What the heck do you mean!
@My5TeRyS
@My5TeRyS 2 года назад
Thanks man, i watched your videos on the subway every day, and it helped me to spend that time studying. I appreciate it and I passed the tests for google, now in team matching!
@messi_codes
@messi_codes 6 месяцев назад
So happy for you brother!
@ashkan.arabim
@ashkan.arabim Месяц назад
I need stuff like this to keep me motivated :)
@countdooku681
@countdooku681 2 года назад
About that part where we reset leftMin to 0 if it's negative. Take for example a string that looks like this "(((***". After we have parsed this string our leftMax wil be 6 and our leftMin will be 0 which should return true because we can change every asterisk symbol for a right parenthesis symbol. But if we add another asterisk to that string "(((****" our leftMin will become -1. But in this case it doesn't make any sense for us to turn every asterisk into a right parenthesis because it will make the whole string invalid, that's why we treat one asterisk as an empty string and reset our leftMin to 0. And we don't afraid of a case like this "())" where we also should reset our leftMin because our leftMax will become less than 0 and it will return false.
@appcolab
@appcolab 2 года назад
Thanks for explaining, it is really a helpful comment
@shavitl.306
@shavitl.306 2 года назад
thanks!
@kritmok1875
@kritmok1875 Год назад
great explanation!
@ancai5498
@ancai5498 Год назад
My two cents on the reset of negative leftMin, basically there're two sources we decrease the values of leftMin: 1. when we meet the ')' 2. encounter '*'. If we have more than enough of ')' leftMax will become negative, and we will directly return false. However, if we don't return, and we get negative leftMin, which means we get more than enough '*' since we can transform the '*' to an empty string, this is how this -1 to 0 comes. For eg, (**
@nehaa3778
@nehaa3778 11 месяцев назад
👍
@rahulprasad8243
@rahulprasad8243 7 месяцев назад
Awesome. Thanks
@johnoh537
@johnoh537 2 года назад
"We are never going to recover from this" i spit out the cherry seeds from laughing hahahaha
@NeetCode
@NeetCode 2 года назад
Lol sometimes I get carried away
@lakshminarayanannandakumar1286
@lakshminarayanannandakumar1286 7 месяцев назад
An intuitive explanation: As we progress through the string, our minimum and maximum counts of unmatched left parentheses (`leftmin` and `leftmax`) dynamically change. If the `leftmin` becomes negative, it indicates that we've encountered more right parentheses than the total number of corresponding left parentheses and asterisks seen so far. In such cases, we can revise the previous characters to include an empty space, utilizing the wildcard '*' as an optional left parenthesis. This gives the string another chance to remain valid. However, if the `leftmax` becomes negative, it signifies an irrecoverable situation. This occurs when, despite using all wildcards as left parentheses, the count of right parentheses exceeds the count of remaining unmatched left parentheses and asterisks. In essence, it means that the string cannot be balanced, rendering it invalid. This approach ensures that the string's validity is continuously monitored and maintained throughout the traversal.
@jans3067
@jans3067 6 месяцев назад
This took a while to fully grasp. No chance I would ever come up with this myself under the pressure of a real interview. That being said tho, now that I do understand it I think this is one of the coolest solutions I’ve ever seen
@ngneerin
@ngneerin 2 года назад
For the first time, i didn't understand your explanation
@nikhilsingh2184
@nikhilsingh2184 2 года назад
Lol
@johnsoto7112
@johnsoto7112 2 года назад
First time I felt this way also
@swarnimvarshneya6944
@swarnimvarshneya6944 6 месяцев назад
I know right. I feel so stuck.
@sheikhmkrifat7749
@sheikhmkrifat7749 3 месяца назад
same here
@ngoquangtrung234
@ngoquangtrung234 6 месяцев назад
This is the most brilliant solution, the mathematical correcteness of this solution is very clear.
@bouzie8000
@bouzie8000 7 месяцев назад
This might be one of the most intelligent solutions I've seen. Never in a million years would I have substituted a backtracking approach for a multi-variable tracker
@NhanSleeptight
@NhanSleeptight 2 года назад
leftMin and leftMax is our possibility range where leftMin is decrease choice, leftMax is increase choice. Since we only care if our leftMin can reach 0, if leftMin < 0, we reset it to 0 to eliminate other invalid possibilities.
@Yopperpo
@Yopperpo 2 года назад
i love you daddy neetcode
@lukealberts.hastings
@lukealberts.hastings Год назад
A good explanation for the reason why we need a special resetting work for and only for leftmin can be: A string can be invalid only if either it contains more left parentheses than right parentheses and vice versa or their positions violate the balance rule. Leftmax can help us detect all possible violations but one: some left parentheses do not have matching right parentheses. We leave this mission to leftmin. We traverse the string for the left to the right, and the leftmin is responsible for recording the most possible choices of the right parenthesis. However, a right parenthesis can never match a left one which is right to it. So, whenever leftmin is less than zero, we will have no other choices apart from considering it(the character we are visiting) not existing and resetting it(leftmin) to zero. By doing that, we assure that we will never match a right parenthesis to a left one which is right to it. Therefore, upon traversing the string, if leftmin is still larger than zero, we can be certain that there are unmatched left parentheses and return false. We can also be certain that every left parenthesis is matched otherwise, and since all possible 'right parenthesis' violations would have been detected by leftmax during the traversal, if we can finish the traversal, it is certain that every right parenthesis is matched, so it's safe to return true
@jaisinghbisht3303
@jaisinghbisht3303 Год назад
Very helpful, thanks
@VarunMittal-viralmutant
@VarunMittal-viralmutant 2 года назад
I was really conflicted about why we reset leftMin whenever we fall below 0, but then convinced myself with this argument: One way to think about this is we do -1 from leftMin only for ) and * And while ) is definitive, * can have 3 possible states. We always assume ) and if we are wrong, then it could be either of the other 2 If c == ) and leftMin < 0, that would mean our assumption that previous * was ) is wrong and it could be "" or ( Eg: (*) or (*)) If c == * and leftMin < 0, that would mean our assumption that * was ) is wrong and it must be "" or )
@onepercentswe
@onepercentswe 2 года назад
Simple argument is, at any point of time we can have count(")")
@kathirchidhambarapandy929
@kathirchidhambarapandy929 10 месяцев назад
if leftmin goes below negative we remove the possibility of that * being left parenthesis because that entire expression will be invalid
@VarunMittal-viralmutant
@VarunMittal-viralmutant Месяц назад
A simpler solution with time complexity = O(n) and space complexity = O(n) ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-KuE_Cn3xhxI.html
@phanthe3471
@phanthe3471 6 месяцев назад
I have this question today as my daily mission and I struggle a lot using stack with 2 times iterating the stack elements. Thanks for your video and I have a better solution with straightforward checking the string valid
@pulkitjain8135
@pulkitjain8135 6 месяцев назад
To understand this question, first see question without wild card with stack and variable approach then with this use two stacks of asstrick and open bracket then you realise you dont need to remember everyone of index of open braces and asstrick just difference between two top values, and if difference is negative at certain point you never gonna make valid string.
@TF2Shows
@TF2Shows 6 месяцев назад
this question should be hard, not medium
@DavidDLee
@DavidDLee Год назад
1. Why is the recursive + caching solution O(N^3) 5:20 ? Seems like it would be same as space complexity O(N^2). 2. The greedy approach is not well explained. Why will it return false iff the string is invalid?
@alexshay7969
@alexshay7969 Год назад
Hi NeetCode, I noticed that this this problem is under "Stack" and the actual code in Java use Stack, but your video explanation is something else. What is preferred?
@aadil6081
@aadil6081 7 месяцев назад
Think of it this way… If you have oversupply of ‘(‘ then you cannot get 0 leftMin value even if you turn all ‘*’ into ‘)’, thats what we did by subtracting 1 from leftMin when we see a ‘*’ If we have oversupply of ‘)’ at any point i in the string then we can’t have a solution even if we turn all ‘*’ into ‘(‘ before point i… that’s where leftMax turns negative If we don’t have oversupply of either ‘(‘ or ‘)’ then we can guarantee that we have a solution
@jhanzaibhumayun5782
@jhanzaibhumayun5782 2 года назад
I'm thinking O(n). You can loop through the array and have a counter that you add 1to if the parenthesis is left and remove 1 if the parenthesis is right. And have a seperate counter for the *. In every interation you check if the parenthesis counter is negative. If it is you make sure that the wildcard counter is bigger than abs(parenthesis counter). And at the last iteration you check if wildcard counter is equal to or bigger than abs(paranthesis counter).
@GingeBreadBoy
@GingeBreadBoy Год назад
This is incorrect, We could have ***(((, this would return True, since # wild == # left, But the position in which we encounter wild cards matters.
@ade1238-r7z
@ade1238-r7z Год назад
I implemented that solution,it failed and then i searched this video LOL
@shashankjoshi8250
@shashankjoshi8250 6 месяцев назад
Just amazing !! Perfect explanation of the thought process involved !!
@stith_pragya
@stith_pragya 5 месяцев назад
Thank You So Much for this wonderful video.......🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@nguyentp2133
@nguyentp2133 2 года назад
Try to understand the greedy idea for hours but it does not work for me intuitively. So I come back to the 2 stacks solution. Thanks for the explanation. I have been using your Neetcode 150 every day since a month ago. Thanks a lot!
@prasad9012
@prasad9012 2 года назад
Can you share the 2 stacks solution?
@nguyentp2133
@nguyentp2133 2 года назад
@@prasad9012 Hope this help ``` class Solution: def checkValidString(self, s: str) -> bool: return self.checkValidString_2stacks(s) def checkValidString_2stacks(self, s: str) -> bool: main, star = [], [] for i, c in enumerate(s): if c == "(": main.append(i) continue if c == "*": star.append(i) continue # if we see a right ), try to cancel the left ( if main: main.pop() elif star and star[-1] < i: star.pop() else: return False # If main stack has left parenthesis, try to cancel it with * while main and star and star[-1] > main[-1]: star.pop() main.pop() # If we cannot cancel the left parenthesis if main: return False # as along as the main stack is empty, we do not care the star anymore. return True ```
@CSBAjay
@CSBAjay 2 года назад
@@nguyentp2133 I prefer this.. this is intuitive one
@BTypeGuy
@BTypeGuy Год назад
@@nguyentp2133 Thanks for this solution. It's much easier to grasp.
@edwin4372
@edwin4372 2 года назад
Hey man, thanks for all your effort and congrats on your recent job! I was wondering if you could make a video for Leetcode problem 2115. Find all Possible Recipes? I'm having a hard time trying to understand it. Thanks
@rohit-ld6fc
@rohit-ld6fc Год назад
if(leftMax < 0 ) return false; // even we selected * as ( still right parenthesis are more then left parenthesis f(leftMin
@vellankiindeevar5530
@vellankiindeevar5530 3 месяца назад
dude how you got this code . that was beautiful . but how would a beginner would get these thoughts ?
@thetech685
@thetech685 3 месяца назад
"we will never recover from this" - yes we will never recover from the trauma this question causes
@moabd7575
@moabd7575 6 месяцев назад
isn't the memoization (dp) solution supposed to be O(N^2) time comp? since we are filling a 2d array of at most size n*n ? this is my solution: (simplified the syntax for non c++ users) bool checkValidString(string s) { int n = s.size(); map dp; // i for index, op means number of opened parenthesis (lrft) bool dfs = (int i, int op){ if(dp.find({i, op})) return dp[{i, op}]; if(op < 0) return false; if(i == n) return op == 0; bool res = false; if(s[i] == '(' ) res = dfs(i+1, op+1); else if(s[i] == ')' ) res = dfs(i+1, op-1); else res = dfs(i+1, op+1) || dfs(i+1, op) || dfs(i+1, op-1); return dp[{i, op}] = res; }; return dfs(0,0); }
@erminiottone
@erminiottone 6 месяцев назад
Also the editorial mention O(n^2) for the solution 2d dp with memoization
@sidazhong2019
@sidazhong2019 11 месяцев назад
DFS is king. Crystal clear logic. Solved in 25ms.
@MadpolygonDEV
@MadpolygonDEV 6 месяцев назад
watched a minute because i thought the question will be hell to solve and I didnt wanna keep duct-taping my solutions but I am glad I stopped and did it myself and it was easier than expected.
@philandros3195
@philandros3195 6 месяцев назад
Just watching the first 2 min of your video, enabled me to solve the problem in a few minutes. I appreciate you setting up the problem coherently, instead of just immediately giving the answer.
@ellerym149
@ellerym149 11 месяцев назад
nice approach! thanks!
@NursultanBegaliev
@NursultanBegaliev 6 месяцев назад
Great solution 👍👍
@jaatharsh
@jaatharsh 10 месяцев назад
there is even a simpler greedy approach using O(n) space for a Stack ''' public class Solution { // Time = Space = O(n) Soln public bool CheckValidString(string s) { Stack open = new Stack(), star = new Stack(); for(int i=0;i0) open.Pop(); else if(star.Count>0) star.Pop(); else return false; while(open.Count>0) if(star.Count==0 || star.Pop() < open.Pop()) return false; return true; } } '''
@leocai7499
@leocai7499 2 года назад
Thanks!
@amitupadhyay6511
@amitupadhyay6511 2 года назад
Some questions are not meant to start your day with
@hanklin4633
@hanklin4633 2 года назад
In the dp with memo solution, I can't understand why we would revisit the same place. In each call, we always increment the i position, in "dps(i+1,...)", so wouldn't we always have different i in the next recursive call, so never will have it in the cache? Only if we decrement i, "dps(i-1,....)" I would think then we might see it already in the cache. What am I missing?
@DavidDLee
@DavidDLee Год назад
But you call dfs multiple times for i + 1, right? Also, every one of these invocations will split into more if another * is found. The end result is many calls to the same position and even with the exact same arguments.
@donaldcodes
@donaldcodes 6 месяцев назад
I tried solving this with DP, there's no way I'd come up with the greedy solution in an interview myself LOL
@yashpathak9285
@yashpathak9285 2 года назад
An easier solution would be to use two stacks.
@joshuadrakes3552
@joshuadrakes3552 2 года назад
True however u sacrifice space
@arjuntt2604
@arjuntt2604 2 года назад
isnt a single counter of type int be the even easier solution?
@yashpathak9285
@yashpathak9285 2 года назад
@@arjuntt2604 I think it's relative.
@zakenmaru8612
@zakenmaru8612 2 года назад
It's more intuitive. I think he's going for a low mem solution here
@arjuntt2604
@arjuntt2604 2 года назад
@@yashpathak9285 i didn't get you,
@asdfasyakitori8514
@asdfasyakitori8514 11 месяцев назад
Great video
@ASWANTHMANCHALA
@ASWANTHMANCHALA 6 месяцев назад
class Solution: def checkValidString(self, s: str) -> bool: c = 0 q = 0 for i in range(len(s)): if s[i] == '*': q += 1 elif s[i] == '(': c += 1 else: if c > 0 : c -= 1 elif q > 0: q -= 1 else: return False c = 0 q = 0 for i in range(len(s)-1, -1, -1): if s[i] == '*': q += 1 elif s[i] == ')': c += 1 else: if c > 0: c -= 1 elif q > 0: q -= 1 else: return False return True
@ibrahimkoz1983
@ibrahimkoz1983 2 года назад
Jesus, this is a tough one.
@aaabcaa
@aaabcaa Год назад
Can anybody explain why the dp solution for this takes o(n^3) ?
@DavidDLee
@DavidDLee Год назад
I think it is a mistake. I think time complexity is O(N^2) too. The cache size, worst-case is O(N^2) because the worst-case combinations of 'i' and 'left', both bounded by N. NeetCode says each cache entry requires x N, but I don't think this is right. Every invocation simply calls itself again, with no loops, etc.
@debmalyakundu4855
@debmalyakundu4855 2 года назад
please make a video on Find the Closest Palindrome
@ancai5498
@ancai5498 Год назад
Couldn't find the link for the DP or memorization solution, can anyone please let me know where I can find it?
@TheLastStand226
@TheLastStand226 6 месяцев назад
The editorial for this problem on leetcode has all the solutions
@gremlan6419
@gremlan6419 2 года назад
Well looks like the greedy solution is not for me lol
@LL-us8ob
@LL-us8ob 2 года назад
really good explanation! thank you
@nikhilrana9825
@nikhilrana9825 2 года назад
You have already uploaded a video of this problem (same kind)
@maxdegreat566
@maxdegreat566 2 года назад
Let him upload two right
@technophile_
@technophile_ Месяц назад
You didn't explain what would happen if we take the * as an empty string when explaining the greedy method.
@dingus2332
@dingus2332 Год назад
I will just go with 2 Stack solution :P
@pranavsharma7479
@pranavsharma7479 2 года назад
lol, this greedy is tuff to come in interviews
@LoganLi-su5ju
@LoganLi-su5ju 5 месяцев назад
The reason we reset the leftMin to 0 when negative is that we can not cancel a future '('. Think about a simple invalid example "*(".
@AbhinavChandel-s4l
@AbhinavChandel-s4l Год назад
bool solve( int i , int cnt , string &s){ if( i == s.length() ){ return cnt == 0; } bool ans = false; if( s[i] == '('){ ans = solve(i+1 , cnt+1 , s); } else if( s[i] == ')' && cnt-1 >= 0){ ans = solve( i+1 , cnt-1 , s); } else{ bool ans2 = false; if( cnt-1 >= 0 ) { ans2 = solve(i+1 , cnt-1 ,s); } ans = solve(i+1 , cnt+1 , s) || solve(i+1 , cnt , s ) || ans2; } return ans; } bool checkValidString(string s) { return solve( 0 , 0 , s); } this recursive relation is not working i want to know why .........plzzz anybody can help me
@arjuntt2604
@arjuntt2604 2 года назад
i fails to understand why one single counter is not enough for this problem, traverse through the string, increment counter for open parenthesis and decrement it for closed parenthesis, if counter goes negative at any time, means invalid, and if counter didn't reach 0 at the end, invalid, isn't this very simple logic enough for this problem? someone please correct me.
@VarunMittal-viralmutant
@VarunMittal-viralmutant 2 года назад
That would be the case only if there were no '*' - wild card. The wild card changes the whole game With your method, (*)) will give 'False' but it's actually True since * can be replaced with (
@naveenprasanthsa3749
@naveenprasanthsa3749 2 года назад
Pls solve the 3rd problem from today's contest.
@atharvameher5880
@atharvameher5880 Год назад
I came up with an easier solution O(n) space O(1) It requires two passes class Solution { public boolean checkValidString(String s) { int conflicts=0; int resolvers=0; for(int i=0;i0)resolvers--; else return false; } else{ conflicts--; } } else resolvers++; } conflicts=0;resolvers=0; for(int i=s.length()-1;i>=0;i--){ if(s.charAt(i)==')'){ conflicts++; } else if(s.charAt(i)=='('){ if(conflicts==0){ if(resolvers>0)resolvers--; else return false; } else{ conflicts--; } } else resolvers++; } return true; } }
@LOKESHE-wi2yd
@LOKESHE-wi2yd 6 месяцев назад
bro i too had the same intuition , but i lacked at extra opening parenthesis , thanks for the code , now i learnt my mistake class Solution { public boolean checkValidString(String s) { int check = 0; int boost = 0; for(int i =0;i
@atharvameher5880
@atharvameher5880 6 месяцев назад
@@LOKESHE-wi2yd ohh nice
@atharvameher5880
@atharvameher5880 6 месяцев назад
@@LOKESHE-wi2yd my brain worked really good 5 months ago now I've got brainrott cannot understand my own code
@ernie2111
@ernie2111 2 года назад
first comment.
@mixshots1801
@mixshots1801 10 месяцев назад
very helpful , very clear, to the point with out confusion explain thans 🫂