Skip to content

Instantly share code, notes, and snippets.

@mathew-fleisch
Created January 12, 2020 23:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mathew-fleisch/1f499602f96af01b2af9cd71c253ee69 to your computer and use it in GitHub Desktop.
Save mathew-fleisch/1f499602f96af01b2af9cd71c253ee69 to your computer and use it in GitHub Desktop.
Balanced Parentheses
matrix = [["(","("],[")",")"]]
matrix1 = [["(","("],["(",")"]]
matrix2 = [["(",")"],[")",")"]]
matrix3 = [["(",")"],["(",")"]]
console.log(`isBalanced(${JSON.stringify(matrix)}) => ${isBalanced(matrix)}`)
console.log(`isBalanced(${JSON.stringify(matrix1)}) => ${isBalanced(matrix1)}`)
console.log(`isBalanced(${JSON.stringify(matrix2)}) => ${isBalanced(matrix2)}`)
console.log(`isBalanced(${JSON.stringify(matrix3)}) => ${isBalanced(matrix3)}`)
function isBalanced(matrix) {
balancedStack = []
for (let x = 0; x < matrix.length; x++){
for (let y = 0; y < matrix[x].length; y++){
switch (matrix[x][y]) {
case "(":
balancedStack.push("(")
break
case ")":
if (balancedStack.length === 0)
return false
balancedStack.pop()
}
}
}
if (balancedStack.length === 0) {
for (let y = 0; y < matrix[0].length; y++){
for (let x = 0; x < matrix.length; x++){
switch (matrix[x][y]) {
case "(":
balancedStack.push("(")
break
case ")":
if (balancedStack.length === 0)
return false
balancedStack.pop()
}
}
}
}
return (balancedStack.length === 0 ? true : false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment