Skip to content

Instantly share code, notes, and snippets.

@NdauwaRafael
Last active December 8, 2022 11:20
Show Gist options
  • Save NdauwaRafael/81db83212c8ef66304ba05491d526cda to your computer and use it in GitHub Desktop.
Save NdauwaRafael/81db83212c8ef66304ba05491d526cda to your computer and use it in GitHub Desktop.
/*
A bracket is considered to be any one of the following characters: ‘(‘ and ‘)’
Given a string of brackets, determine whether the string is balanced.
If a string is balanced, return YES. Otherwise, return NO.
A string is considered balanced if for every opening bracket there is a closing bracket
in the correct order.
*/
/**
* Examples of balanced strings
* “()”
* “(()())”
* “(()(()))”
*
* Examples of unbalanced strings
* “)(“
* “((())()”
* “())(“
* “))((()”
* "())(()()"
* "()))()((()"
*/
const balancedBrackets = (brackets)=> {
let bracketsArray = brackets.split('');
let pairs = [];
for (let i = 0; i<bracketsArray.length; i++){
if(bracketsArray[i] === '(') {
pairs.push('(');
}
if(bracketsArray[i] === ')'){
if (pairs.length > 0){
pairs.pop();
}
else {
return 'NO';
}
}
}
return pairs.length === 0 ? 'YES' : 'NO';
}
console.log(balancedBrackets('()))()((()')) // ===> NO
console.log(balancedBrackets('(()(()))')) // ===> YES
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment