Determining if a String of Parentheses is Balanced

This technical problem deals with determining whether a string of parentheses is balanced. A string is considered balanced if there are an equal number of open and closed parentheses, and each open parentheses is matched with a closed parentheses.

Problem

Given a string of parentheses, write a function to determine whether the string is balanced. A string is balanced if there are an equal number of open and closed parentheses, and each open parentheses is matched with a closed parentheses.
Example input: "((()))"
Example output: true
Example input: "()())"
Example output: false

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
function isBalanced(str) {
  let open = 0;
  let closed = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") {
      open++;
    } else if (str[i] === ")") {
      closed++;
    }
  }
  return open === closed;
}

// This solution is optimal because it only iterates through the string once, and it does not use any extra space.

A.I. Evaluation of the Solution

This solution is correct and demonstrates a good understanding of the problem. The approach is simple and efficient, and the code is clean and easy to read.

Evaluated at: 2022-11-26 02:16:54