Using JavaScript to validate parentheses

Let’s explore how we can use JavaScript to determine whether or not a string containing parentheses, square brackets, and/or curly braces has an equal number of opening and closing brackets/braces. Essentially we’re going to determine if a string such as (){}[] is valid.

Essentially, each opening bracket or brace needs to have a corresponding closing bracket or brace.

First, let’s take a look at the code in its entirety:

const isValid = (s) => {
    const remaining = [];
    const legend = {
        "(" : ")",
        "{" : "}",
        "[" : "]",
    };
    
    for (let i = 0; i < s.length; i++) {
        if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
            remaining.push(s[i])
        } else if (legend[remaining.pop()] !== s[i]) {
            return false;
        }
    }
    return remaining.length ? false : true;
};

isValid("()[]{}");

We begin by defining an empty array that is going to serve as a “pseudo stack” in which we are pushing/popping elements from as we traverse the given string. We also define a legend object, which is simply a key/value collection of each opening bracket/brace and its associated closing element.

We will utilize a traditional for loop that will traverse the input string and within each iteration of the loop we will perform two checks:

  1. If the current character of the input string s[i] is equal to any opening bracket/brace we will push it into the remaining array.
  2. Else, if the last character from the remaining array DOES NOT equal the current character, we return false;

If the second condition is never encountered, we reach the end of the string and then do one final comparison where we look to see if there are any remaining elements in the array. If so, we return false. This last check essentially checks for any orphaned brackets that might have resulted from the input string be an odd length.

One possible alternative solution to this last check is to do the odd check at the very start of the function and immediately return false if the length is determined to be odd. If this is the case, we can safely assume that at least one bracket/brace doesn’t have a valid closing bracket/brace. It would look like this:

const isValid = (s) => {
    if (s.length % 2 !== 0) return false;
    const remaining = [];
    const legend = {
        "(" : ")",
        "{" : "}",
        "[" : "]",
    };
    
    for (let i = 0; i < s.length; i++) {
        if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
            remaining.push(s[i])
        } else if (legend[remaining.pop()] !== s[i]) {
            return false;
        }
    }
    return true;
};

isValid("()[]{}");