LeetCode 20. Valid Parentheses Solution Explained - Java

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

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

  • @prakash_reddy4
    @prakash_reddy4 2 года назад +179

    For cases like "( [ } } ] )" we should add a else block to return false. Code Below:
    class Solution {
    public boolean isValid(String s) {
    if(s.length() % 2 != 0){
    return false; //base case, all elements need to have a pair. So total count should be even
    }

    Stack stack = new Stack();
    for(char c: s.toCharArray()){
    if(c == '(' || c == '[' || c == '{'){ //push all opening braces to stack & compare them with closed ones later.
    stack.push(c);
    }
    else if(c == ')' && !stack.isEmpty() && stack.peek() == '(' ){ //if top element in stack is ( and given element is ) then remove that pair.
    stack.pop();
    }
    else if(c == ']' && !stack.isEmpty() && stack.peek() == '[') {
    stack.pop();
    }
    else if(c == '}' && !stack.isEmpty() && stack.peek() == '{') {
    stack.pop();
    }
    else{
    return false; //when cases like }}, )), ([}}]) this will return false
    } //stack.push(c)
    }
    return stack.isEmpty(); //when every pair is removed then stack becomes empty & it is true. else false
    }
    }

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

      yes, you are absolutely correct !!!

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

      thanks man. i was looking for this

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

      great clarification, thanks!

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

      Noticed that as well.

    • @Martin-qy3mm
      @Martin-qy3mm 2 года назад +4

      Also in case if the string starts with a closing parentes the "else return false" statement would catch that

  • @TrinhPham-um6tl
    @TrinhPham-um6tl 4 года назад +94

    Your code does not work if the testcase is ")}" or any testcases which contain only closing brackets because of your If-Else Statements. It would be better if you add the command: " else stack.push(c); ". Thank you for your contribution!

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

      yes, helped me

    • @alextrex3975
      @alextrex3975 4 года назад +5

      Thank you! this is the last missing logic

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

      yes! thank you :)

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

      Thanks for this fix. Mine was failing on " ( [ } } ] ) ".
      Because the stack was not empty, it wasn't doing anything to register the invalid closing parenth

    • @x99teco99x
      @x99teco99x 2 года назад +6

      added else return false

  • @alexlun4464
    @alexlun4464 4 года назад +10

    Hey... I don't know if it was a bug in leetcode, but that code of yours doesn't work anymore. In order to make it work, you need to add a final 'else return false' at the end.
    That's becuase that code doesn't handle situtions like this " [ ) ) ]". The double closing parantheses get completely ignored as there's no case that handles them, and they shouldn't get ignored.

    • @meezanshaikh6692
      @meezanshaikh6692 4 года назад +1

      add else stack.push(c) after last else if

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

      Yes you are correct

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

    not being accepted on leetcode

  • @AamirBilalm
    @AamirBilalm 3 года назад +18

    This will fail for a case like "( [ } } ] )". We need to add one else statement where we push the character into the stack.

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

      I was wondering the same thing, this code needs a last `else {stack.push(c)}` but how does this gets passed in leetcode? was this testcase added later?

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

      @@youshamahmood3183 not working in my leet code

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

      class Solution {
      public boolean isValid(String s) {
      if (s.length()%2!=0) return false;
      Stack stack=new Stack();
      for(char c:s.toCharArray()){
      if(c=='('|| c=='{'|| c=='['){
      stack.push(c);
      }else if (c==')' && !stack.isEmpty() && stack.peek()=='('){
      stack.pop();
      }else if(c=='}' && !stack.isEmpty() && stack.peek()=='{'){
      stack.pop();
      }else if(c==']' && !stack.isEmpty() && stack.peek()=='['){
      stack.pop();
      }
      else return false;
      }
      return stack.isEmpty();
      }
      }

  • @mdkarim831
    @mdkarim831 4 года назад +32

    This will give the wrong answer for "))". There should be an else: return False

    • @yuchenhu483
      @yuchenhu483 4 года назад +1

      Yes, its surprising the code passed the test. When I run it on idea, it gives me the wrong answer with"()]]".

    • @meezanshaikh6692
      @meezanshaikh6692 4 года назад +7

      @@yuchenhu483 add else stack.push(c) after last else if

    • @KM-zd6dq
      @KM-zd6dq 3 года назад +4

      yep remember to add "else return false;" on your last line of the for loop

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

      @@KM-zd6dq yes I did also faced the same issue

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

      @@meezanshaikh6692 Thanks makes sense

  • @muhammadrahmatullahrahman1534
    @muhammadrahmatullahrahman1534 4 года назад +7

    Good video, however if all the input is closing brackets with even quantity, it won't pass the test. for example the input is "}}", my suggestion is we can put else branch at the end where we basically just return false. since we know that the first input will be a closing bracket.

    • @thomaswang1670
      @thomaswang1670 4 года назад

      yeah i think you are right. I have the same question

    • @anmoldua9755
      @anmoldua9755 4 года назад

      I think leetcode doesn't account these test cases.. they should have accounted for these

  • @jaya4155
    @jaya4155 2 года назад +14

    Thanks Nick .Great explanation.This solution is failing for few test cases.example - "([}}])".We need to push to stack on line number 15.

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

      For better runtime, return false on line 15

  • @ИванЖалдак-ю8у
    @ИванЖалдак-ю8у 3 года назад

    Tried to solve it myself without stack. Took an hour or two, runtime 1ms, memory 37 MB. Code length much longer than this. Watched video, reproducesd the solution on LeetCode. Got the same 1ms and 37 MB, but code is three times shorter, which is a big win.

    • @abd0-omar420
      @abd0-omar420 2 года назад

      Can you tell me the solution without stack if you don't mind and thank you

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

    solution doesn't work for "([}}])" not currently accepted by leetcode

    • @Ram-vg5fu
      @Ram-vg5fu 4 года назад

      Same here can u please help

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

      ​@@Ram-vg5fu Just add on an else statement at the end of all the else if's. You can put a counter that increments if any case goes there. Then have a check to see if the counter is greater than 0, if it is return false. Boom. Solved.

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

      Hi @Jenna,
      Below code works perfectly for leetcode.
      static boolean validateByMap(String s){
      HashMap map = new HashMap();
      map.put('(', ')');
      map.put('[', ']');
      map.put('{', '}');
      Stack stack = new Stack();
      for (int i = 0; i < s.length(); i++) {
      char curr = s.charAt(i);
      if (map.keySet().contains(curr)) {
      stack.push(curr);
      } else if (map.values().contains(curr)) {
      if (!stack.empty() && map.get(stack.peek()) == curr) {
      stack.pop();
      } else {
      return false;
      }
      }
      }
      return stack.empty();
      }

  • @ehsanhosseini5861
    @ehsanhosseini5861 4 года назад +6

    Your videos are awesome, great explanation. I Have a few questions not related to this video but for interview preparation.
    I already did about 70 leet code but after a month when I look at the same problem I solved it I don't remember which algorithm I used and it takes me 30 mins or one hour to solve it again. Is this normal? Can you please guide me in these 3 questions:
    1. When were you looking at the correct solution -- before you began the problem when you got stuck, only after struggling to solve it yourself? How long until you would look at the solution, typically?
    2. What would you do after you'd not solved the problem, but looked at the answer?
    3. What would you do after you did solve a problem?

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

    Use a hash table instead of if else's, way cleaner. The core of the algo is still the same, the pushes and the pops have to match up

  • @riyayadav-wz4lf
    @riyayadav-wz4lf 2 года назад

    What would be the time complexity of this solution?

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

    your code fails on "([}}])" test case. I am also using leetcode may they now added some more test cases.

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

    add else{ return false;} after all else if statements

  • @rayprusia4753
    @rayprusia4753 5 лет назад +8

    I appreciate all you hard work and help us.

  • @alextrex3975
    @alextrex3975 4 года назад +8

    Uhh, this doesn't work for test case: "([}}])"

    • @ojasvichaudhary8724
      @ojasvichaudhary8724 4 года назад +22

      simply add this condition after else if conditions
      else {
      return false ;
      }

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

    if we take test case as "}])"what will it return ?

  • @fatihcatpinar890
    @fatihcatpinar890 4 года назад +1

    As others mentioned, great video but the code does not consider the case if the input is all closing parentheses. One possible fix is adding an additional 'else if' right after the if statement that checks if the char is a closing parenthesis and the stack is empty, if both satisfy it can return False.

  • @shubhamjain5505
    @shubhamjain5505 4 года назад +1

    Thanks Nick for the explanation ! Can we use map instead of multiple if else conditions ?

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

      Yes you can.

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

      However, a map would be O(n) space complexity as opposed to the else if which is O(1)

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

    Good explanation, Thank you! I've a question, what if many brackets are there, using if-else or switch checking the closing brackets many times is good? And, another question is that instead of if-else/switch, how abt using hashmap for checking opening brackets the same with atop element in the stack?

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

    It seems to be that your code does not consider input like this ")" ? ?

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

    if this is the string given "{ [ ] } ]" this solution gives wrong answer. Thank you for your contribution!

  • @vighneshk509
    @vighneshk509 4 года назад +1

    why did you include CONDITION TO CHECK IF STACK IS EMPTY OR NOT?? BCOZ IF IT HAD BEEN EMPTY STACK.PEEK WOULD NOT HAVE TAKEN PLACE !! SO WY SPECIFY IT??

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

      If it runs stack.peek() when stack is empty it throws an exception, so you need to check first.

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

    time complexity?

  • @Rohitdec01
    @Rohitdec01 4 года назад +1

    Add the below as well
    else return false; // To handle (})

  • @nishantsharma3100
    @nishantsharma3100 4 года назад +1

    your soln is giving "bad operand types for binary operator '||' .in line 7

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

    Looks like LC updated test cases.
    Comment Line #3. Added below after line #15. With this we can extend this test case IDE design problem. For ex -
    Test case - {print (hello World)} - PASS
    - 3 //if (s.length() % 2 !=0) return false;
    +16 else if (c =='(' || c =='{' || c=='[' || c =='}' || c==')' || c ==']') {
    +17 return false;
    +18 }

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

    left ear enjoyed this

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

    if we find c == ')' while the stack is empty, what will happen?

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

      Or, when we find c == ')' and stack is empty, but the peek() is not '(', what do we do?

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

      Okay, think i know the answer, just add else return false at the end of else if conditions. Thanks for the video!

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

    Thank you, Nick, for explaining!

  • @Aman-w1z3b
    @Aman-w1z3b 23 дня назад

    Modified code for all test cases:-
    class Solution {
    public boolean isValid(String s) {
    if(s.length()%2!=0){
    return false;
    }
    Stack stack = new Stack();
    for(char c:s.toCharArray()){
    if(c=='(' || c=='{' || c=='['){
    stack.push(c);
    }else if(c==')' && !stack.isEmpty() && stack.peek()=='('){
    stack.pop();
    }else if(c=='}' && !stack.isEmpty() && stack.peek()=='{'){
    stack.pop();
    }else if(c==']' && !stack.isEmpty() && stack.peek()=='['){
    stack.pop();
    }else{
    stack.push(c);
    }
    }
    return stack.isEmpty();
    }
    }

  • @chocolateandmath497
    @chocolateandmath497 5 лет назад +1

    What does stack.peek() return?
    How does it run through the case "{[]}"?
    Fun video!! Great job :D

    • @MistaT44
      @MistaT44 5 лет назад +7

      ChocolateAndMath stack.peek() returns the value at the top of the stack. For ‘{[]}’
      It pushes { and [ to the stack. Then it gets to the ] conditional. Since the top of the stack at the moment is its corresponding opening bracket [, it removes the opening bracket. The only bracket remaining in stack is { now. Then the next iteration, c is } and checks the top of stack, it matches { and pops it off. Now the Stack is empty voila

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

    Hey Nick, really awesome explanation. I hope you can keep doing these videos

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

    confusion.CLEARED(); THANK YOU!

  • @AbhishekKumar-md4ul
    @AbhishekKumar-md4ul 3 года назад

    will this code work for ( ] )

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

    Good explanation but sadly this code doesn't work for the case " ( [ } } ] ) " , requires an extra else block to return false.

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

    line 3 wont work if input = '((()'

  • @AbhinavKumar-dr4ef
    @AbhinavKumar-dr4ef 2 года назад

    class Solution {
    public boolean isValid(String s) {
    if(s== null)
    return false;
    int length = s.length();
    if(length %2 ==1)
    return false;
    Stack stack = new Stack();
    for(int i=0; i< s.length(); i++)
    {
    boolean check = false;
    if(s.charAt(i)=='(' || s.charAt(i)=='{' || s.charAt(i)=='[')
    {
    stack.push(s.charAt(i));
    check = true;
    }
    // Do not peek empty stack to avoid exception
    if(s.charAt(i)==')' && !stack.isEmpty() && stack.peek()=='(')
    {
    stack.pop();
    check = true;
    }
    if(s.charAt(i)=='}' && !stack.isEmpty() && stack.peek()=='{')
    {
    stack.pop();
    check = true;
    }
    if(s.charAt(i)==']' && !stack.isEmpty() && stack.peek()=='[')
    {
    stack.pop();
    check = true;
    }
    if(check == false)
    return false;
    }
    return stack.isEmpty();
    }
    }

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

    thanks for good explanation :D

  • @GG-hk5iz
    @GG-hk5iz 5 лет назад +1

    Thanks Nick

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

    great explanation

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

    You have missed one last else block for some cases like "( [ } } ] )"

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

    Thank you very much for all your videos..for pattern "([}}])" this code does not work.. add "else false;" condition to it.. this is basically you not popping anything from stack even if you get closing bracket.. so we can stop here and return false..

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

    left ear left the chat.
    right ear never entered the chat.

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

    there should be another condition for returning the false, as for the case '([ {{ ])' , the code pushes ([ to the stack and checks if } is present at the peek of stack and does not pops then again checks for another } and verifies if corresponding { is also not there in the stack and does not pops the element which in both of the above cases should return false, and finally verifies ] and ) and pops simultaneously verifying them present at the peek and returns true for stack to be empty, which is a *WRONG* solution either a condition to be added to return false if any of the above condition is not satisfied!! """ else return false; """ or either we can push that element to the stack """ else stack.push(c); """

  • @turki8542
    @turki8542 4 года назад +1

    you are the best thanks!

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

    I remember doing this and got stuck why is it wrong.
    The genius in me realized about 30 mins later that the open and close parenthesis are not palindromes...

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

    Your code is wrong for cases such as '}}"

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

    Great and clear solution! Thanks! Although it passes Leetcode, I think we should add "else return false" after the last "else if". Since (])] should be false, however the code in the video would not recognize that it is false.

    • @meezanshaikh6692
      @meezanshaikh6692 4 года назад

      else stack.push(c) will work too

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

      @@meezanshaikh6692 it will not work if first element is any closing bracket

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

      @@nileshpatil3710 yes. I was a bad coder last year 🤐

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

    correction
    class Solution {
    public boolean isValid(String s) {
    if(s.length() % 2 != 0){
    return false;
    }
    Stack stack = new Stack();
    for(char c : s.toCharArray()){
    if(c == '(' || c == '[' || c == '{'){
    stack.push(c);
    } else if(c == ')' && !stack.isEmpty() && stack.peek() == '('){
    stack.pop();
    } else if(c == '}' && !stack.isEmpty() && stack.peek() == '{'){
    stack.pop();
    } else if(c == ']' && !stack.isEmpty() && stack.peek() == '['){
    stack.pop();
    } else{
    stack.push(c);
    }
    }
    return stack.isEmpty();
    }
    }

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

    I just did it the same way just forgot to pop in the last. Damn it.

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

    ("(abc())") i got this in my tests so using stack wont work any ideas how to go about this one?

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

    return false in else condition.

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

    🤩🤩🤩🤩🤩🤩🤩🤩🤩🤩🤩 Thank you so much
    Bro

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

    else { return false;}

  • @-Corvo_Attano
    @-Corvo_Attano 2 года назад

    Thanks man :)

  • @mostafahegazy2186
    @mostafahegazy2186 4 года назад +1

    wrong answer

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

    Please correct the mistake....

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

    Brilliant

  • @דניאל-ט9ד
    @דניאל-ט9ד 3 года назад

    GREAT VIEO.

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

    Get your code

  • @TheYamaor
    @TheYamaor 4 года назад

    Tnx Man !

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

    This code does not works for the single string "]" or "}" or ")"

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

    I'd love to see this problem solved using recursion

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

    This solution fails 4 test cases

  • @mr.erikchun5863
    @mr.erikchun5863 Год назад

    this is wrong

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

    he has zero knowledge. just copies solutions.

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

    great explanation

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

    Great explanation