Validate Parenthesis In a String (Coding interview problem) - Whiteboard Thursday

  Рет қаралды 25,903

Irfan Baqui

Irfan Baqui

Күн бұрын

Check out the detailed data structures and algorithms course at www.interviewaccelerator.com
Today's problem is about validating parentheses. All good code editors need a way to tell you whether your code has the right set of parentheses. We will implement an algorithm that does just that.
Also look out for next week's problem that I mention in the video. Try it out yourself and subscribe to get notified when the solution comes out.

Пікірлер: 36
@Bojl95
@Bojl95 6 жыл бұрын
just wanna thank you for all these videos man, they really help me out throughout this tough process
@varungirdhar3840
@varungirdhar3840 6 жыл бұрын
Exactly what I was looking for. Keep Going. Thanks allot for simplifying such problems!
@tannerbarcelos6880
@tannerbarcelos6880 3 жыл бұрын
I like this solution a lot. I knew I wanted to use a stack, but I was doing if statements of all the checks for closing matches and the code was really messy. The maps make the code super compact when doing the basic checks. Great work
@locky2127
@locky2127 6 жыл бұрын
We had this question on one of our tests for 1 point on my first semester of the first year of programming at university.
@vinayakgupta1
@vinayakgupta1 5 жыл бұрын
You make things look so easy!!! Great Job Please solve the hard questions of leetcode.......
@MRTUnplugged
@MRTUnplugged 5 жыл бұрын
amazing stuff mahn !! keep going :)
@gopalrajpurohit879
@gopalrajpurohit879 6 жыл бұрын
It is possible to perform stack operations on the given array itself, without changing input by three indices. In which case, we can do this in O(1) space complexity and O(n) time complexity. Also in case of single type of parenthesis only, it can simply be done with counter, where counter increments on left parenthesis and decrements on right parenthesis. Any time counter goes below zero.... we an return false. At the end counter need to be zero, else again return false.
@ScutUrsula
@ScutUrsula 6 жыл бұрын
i was thinking exactly the same way :D
@nipunkakshal3696
@nipunkakshal3696 5 жыл бұрын
I am not getting how the else if () is gonna return any boolean .. it will just return the value for the key provided .. any idea ?
@rajeshkumar1149
@rajeshkumar1149 6 жыл бұрын
Hey great videos.a small suggestion ..it would be more helpful if you add a small explanation of why you chose that particular data structure for that problem and what performance benefits that particular ds has in terms of complexity
@wulymammoth
@wulymammoth 6 жыл бұрын
noprobs I think here it’s implied. He mentioned we wanted to know the “last” opening paren. With practice, we should intuitively be searching for some data structures that supports constant time lookup for last.
@andreandrews6237
@andreandrews6237 5 жыл бұрын
so before watching this video, I'm thinking I'd do something like create a char dictionary (c#) of open parens as keys with the value being the closed parenthesis. From there it should be as simple as checking for the compliment (maybe using wrong term). Example (syntax could be off, but you should get it): bool valid = true; int opposite = str.Length - 1; dictionary dict = new dictionary(insert key,value pairs); for(int i = 0; i
@Endede
@Endede 4 жыл бұрын
What does your solution return for "([]{})"?
@ScutUrsula
@ScutUrsula 6 жыл бұрын
A simple approach is to use 3 integers (one for each type of parenthesis), initialize all integers to 0 and add +1 when you find an open parenthesis (only if the actual value of that integer is >= 0, otherwise you already had an open parenthesis of that type, so the string is already invalid) and subtract -1 when you find a closed parenthesis. At the end check all 3 integers to be 0 so that the sting is valid. If any of the integers is not 0, the sting is invalid.
@wulymammoth
@wulymammoth 6 жыл бұрын
Geronymo nice. This will being the space complexity down to O(1)
@dragon9786
@dragon9786 6 жыл бұрын
Your solution won't work. If I have a string like ({[})] you will never have a negative integer during the loop and when the loop exits all values will be 0. However the string is not a valid combination of parentheses
@wulymammoth
@wulymammoth 6 жыл бұрын
Good catch, @dragon9786! @Geronymo, I guess this heuristic is invalidated, because it only checks that there are matching closing parens, but discounts the ordering in a problem where ordering does matter. When encountering a closing paren, like `)`, we need to ensure that the last opening paren was `(`, because something like `({)}` would bring the counts back to zero, but is invalid. If we know that we have only uniform opening parens and closing parens, then the algorithm would work.
@ScutUrsula
@ScutUrsula 6 жыл бұрын
I see now, my mistake. My approach was not taking in account for that possibility indeed, so it is an invalid solution to this problem. It only works if the closing parentheses are the same type as the last opening ones
@fawadhassan9036
@fawadhassan9036 2 жыл бұрын
When are new videos coming
@pratapdafedar7305
@pratapdafedar7305 6 жыл бұрын
@Irfan Baqui, How about this solution with space complexity = 1? parenthesis = 0; foreach(char ch in string) { switch(ch) { case '{': case '(': parenthesis ++; break; case '}': case ')': parenthesis --; break; } if(parenthesis < 0) { break; } //break from loop + optimisation. } if (parenthesis == 0) print("Equal"); else print("Not equal");
@justmark8040
@justmark8040 6 жыл бұрын
The problem is not only to checking if the amount of opening parenthesis is equal to the amount of closing ones, you also have to check if they are correct. For example "( { ) }" should be incorrect, but your code says it's correct.
@carlosmacias4230
@carlosmacias4230 6 жыл бұрын
There is a bug in the code if a string starts with a closing parenthesis it would try to pop from an empty stack. I guess if the stack returns null in this case it wouldn't be a bug.
@wulymammoth
@wulymammoth 6 жыл бұрын
Carlos Macias this is what I was going to note, except he accounts for that by checking for the condition you’ve stated, but I believe that if the string starts with an opening paren, we could also exit early and return false
@patilmeghesh91
@patilmeghesh91 6 жыл бұрын
Y do we need a hash table or a dictionary, can v not use only a stack and a bunch of if else statements?
@stewartzayat7526
@stewartzayat7526 6 жыл бұрын
Theoretically, you could do everything with just ifs, that's how it was made after all, but you should also aim for readability of your code.
@anibalasubramaniam4153
@anibalasubramaniam4153 5 жыл бұрын
Agreed, this is like parsing an expression except the only operator possible is concatenation.
@deeppatel1654
@deeppatel1654 4 жыл бұрын
I did something like this //Stack To store last found parenthesis Stack open=new Stack(); //Hashmap to check if corresponding open parenthesis exist in stack HashMap close = new HashMap(); close.put('}', '{'); close.put(']', '['); close.put(')', ')'); //counter for number of parenthesis int count=0; //For loop to traverse the input String for(int i=0;i
@vishal-sg1np
@vishal-sg1np 6 жыл бұрын
Please write with dark colour sketch , your writing is not clear
@ridhwaans
@ridhwaans 5 жыл бұрын
In this problem, can you use a two pointers approach, to read parenthesis left and right? If it finds a pair, it will find the next pair with two pointers
@aadhia9685
@aadhia9685 6 жыл бұрын
Please use another colour sketch....please use low brightness... didnt understand wt ur writing....i have been following ur videos daily...
@carpediemscrate1923
@carpediemscrate1923 4 жыл бұрын
am going to a lots of videos for this.. why u all not showing exact python program.. I didn't get this.. may be am the only dumb person here. I understand what will happen in algorithm. but I need program.. sorry man.. I just helpless!!
@samarthtandon2163
@samarthtandon2163 5 жыл бұрын
I also solve this problem using stacks.....
MEGA BOXES ARE BACK!!!
08:53
Brawl Stars
Рет қаралды 35 МЛН
When You Get Ran Over By A Car...
00:15
Jojo Sim
Рет қаралды 11 МЛН
터키아이스크림🇹🇷🍦Turkish ice cream #funny #shorts
00:26
Byungari 병아리언니
Рет қаралды 28 МЛН
Find the intersection between arrays: Coding Interview Question
11:26
Facebook Interview: K Most Frequent Elements - Whiteboard Thursday
14:24
Largest Square of 1's in A Matrix (Dynamic Programming)
20:43
Irfan Baqui
Рет қаралды 142 М.
Amazon Coding Interview Question - Recursive Staircase Problem
20:01
Coding Interview: Reverse Array in Place - Whiteboard Thursday
7:07
Choose a phone for your mom
0:20
ChooseGift
Рет қаралды 1,9 МЛН
Low Price Best 👌 China Mobile 📱
0:42
Tech Official
Рет қаралды 719 М.
Собери ПК и Получи 10,000₽
1:00
build monsters
Рет қаралды 2,1 МЛН
Simple maintenance. #leddisplay #ledscreen #ledwall #ledmodule #ledinstallation
0:19
LED Screen Factory-EagerLED
Рет қаралды 15 МЛН