Codewars: Valid Parentheses

Nilesh Saini
2 min readFeb 10, 2021

--

Problem: Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.

Examples:

"()"              =>  true
")(()))" => false
"(" => false
"(())((()())())" => true
  1. In my solution to this problem, I have modified the code a little bit. In my solution, you can add any parentheses eg: (), {}, []. No worries it’s just an ‘or statement’.

// If we have an opening paren then we add it to stack

// If it’s a closing paren then pop from stack.
//If the popped element from the stack, which is the last opening paren doesn’t match the corresponding closing paren in the map, then return false

// If the length of the stack is not zero return false

function validParentheses(parens){
let stack = [];
let map = {
'(' : ')',
'{' : '}',
'[' : ']'
}

for (var s of parens) {
if (s === '(' || s === '{' || s === '[' ) {stack.push(s)}
else {let last = stack.pop(); if(s !== map[last]){return false}; }
}
if(stack.length !== 0) {return false}
return true;
}

2. Using Regular expressions:

function validParentheses(parens){
var re = /\(\)/;
while (re.test(parens)) parens = parens.replace(re, "");
return !parens;
}

3. Using Ternary Operator:

function validParentheses(parens){
var result = 0;

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

return (result == 0);
}

Thank You for reading!

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

Responses (1)