Check if a string of parentheses is balanced.

Given a string of parentheses, this function determines whether the string is balanced. A string is balanced if each opening parentheses is matched by a closing parentheses. For example, the input "(())" would return True, while the input "())(" would return False.

Problem

Given a string of parentheses, write a function to determine whether the string is balanced. A string is balanced if each opening parentheses is matched by a closing 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 count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") {
      count++;
    } else if (str[i] === ")") {
      count--;
    }
    if (count < 0) {
      return false;
    }
  }
  return count === 0;
}

// This solution is optimal because it only iterates through the string once.
// It also uses a counter to keep track of the number of open parentheses.
// If the counter ever goes below 0, then we know that there is a closing parentheses without an opening parentheses.
// If the counter is ever greater than 0, then we know that there is an opening parentheses without a closing parentheses.
// If the counter is ever 0, then we know that the string is balanced.

A.I. Evaluation of the Solution

This is a great solution! The candidate has thought through the problem and has come up with a very efficient solution.

Evaluated at: 2022-11-28 12:15:36