Balanced Parentheses in JavaScript

JavaScript

Determine if a string of parentheses is balanced:

You can use a simple algorithm involving a stack to determine if a string of parentheses is balanced in JavaScript. Here's a function to achieve that:

js Copy Code
function isBalancedParentheses(e) {
    let n = [],
        s = ["(", "[", "{"],
        l = [")", "]", "}"];
    for (let a of e)
      // Push opening parentheses onto the stack
        if (s.includes(a)) n.push(a);
        else if (l.includes(a)) {
          // Pop the last opening parenthesis from the stack
        let i = n.pop();

// If the parentheses are not balanced
        if (!i || s.indexOf(i) !== l.indexOf(a)) return !1 
    }
  // If the stack is empty, all parentheses are balanced
    return 0 === n.length
}

// Example usage:
console.log(isBalancedParentheses("()"));
console.log(isBalancedParentheses("()[]{}"));
console.log(isBalancedParentheses("(]"));
console.log(isBalancedParentheses("([)]"));
Output:
true
true
false
false

Explanation:

1. We iterate through each character of the input string.

2. If a character is an opening parenthesis, we push it onto the stack.

3. If a character is a closing parenthesis, we pop the last opening parenthesis from the stack and check if it matches the current closing parenthesis. If they don't match or if there's no corresponding opening parenthesis, the parentheses are not balanced.

4. After processing all characters, if the stack is empty, it means all parentheses are balanced. Otherwise, if the stack is not empty, there are unmatched opening parentheses, so the parentheses are not balanced.

Note This function returns 'true' if the parentheses are balanced and 'false' otherwise.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.