Ad
  • Custom User Avatar

    Hi, I did the Valid Parentheses challenge, where you're supposed to write a function that tells whether a bunch of parentheses are grouped together correctly. () should be true, )( should be false, ()) should be false, etc. I solved the challenge, but I like to look at other peoples' answers to see how I could've done better. I don't understand how the top answer works successfully.
    Here is the code:
    function validParentheses(parens){
    var indent = 0;

    for (var i = 0 ; i < parens.length && indent >= 0; i++) {
    indent += (parens[i] == '(') ? 1 : -1;
    }

    return (indent == 0);
    }
    When I try to think through it, it seems like the code would return )()( as true, even though it's false. However, when I ran the code it correctly returned it as false. Can someone explain to me how the code works so that the proper result is returned in this case?