0

I'm trying to solve the Valid Parentheses, and as described in title, I can't figure how to Array.push to work in this context.

function isValidPar(par){
  var stack = [];
  var length = par.length;
  
  for (var i=0; i<length; i++) {
    var p = par[i];
    if(p === "(" || p === "{" || p === "[") {
      stack.push(p);
    } else if(p === ")") {
        if(stack.length === 0 || stack[stack.length-1] != "(") {return false}
          stack.pop();
      } else if(p === "]") {
          if(stack.length === 0 || stack[stack.length-1] != "[") {return false}
            stack.pop();
      } else if(p === "}") {
          if(stack.length === 0 || stack[stack.length-1] != "{") {return false}
            stack.pop();
    } return stack.length === 0;
  }
}

If I console.log right after stack.push(), then it shows the element I just inserted. But when I try it anywhere else, like inside else if statements or before return, it seems like the array is empty.

3
  • 3
    Haven't read through all of it, but could it be that your return statement is one block too deep? Commented Oct 4, 2017 at 12:03
  • It could be you put it after pop. Commented Oct 4, 2017 at 12:05
  • 1
    Your for loop will have only one iteration because you've put a return statement at the end of it. Commented Oct 4, 2017 at 12:05

1 Answer 1

4

Here is a corrected version of your code

function isValidPar(par){
  var stack = [];
  var length = par.length;
  
  for (var i=0; i<length; i++) {
    var p = par[i];
    if(p === "(" || p === "{" || p === "[") {
      stack.push(p);
    } else if(p === ")") {
        if(stack.length === 0 || stack[stack.length-1] != "(") {return false}
          stack.pop();
      } else if(p === "]") {
          if(stack.length === 0 || stack[stack.length-1] != "[") {return false}
            stack.pop();
      } else if(p === "}") {
          if(stack.length === 0 || stack[stack.length-1] != "{") {return false}
            stack.pop();
    } 
  }
  return stack.length === 0;
}

console.log(isValidPar('(())'));

return stack.length === 0;

should be checked once the for loop is finished

Sign up to request clarification or add additional context in comments.

1 Comment

That was an absurd mistake! Thank you so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.