Search⌘ K
AI Features

Solution Review: Balance Parenthesis

Explore how to use recursion to determine if an array of parentheses is balanced. Learn the role of tracking indices and base cases to match opening and closing symbols correctly. This lesson helps you apply recursion techniques to solve common array problems in coding interviews.

Solution: Using Recursion

Javascript (babel-node)
function balanced(testVariable, startIndex = 0, currentIndex = 0) {
// Base case1 and 2
if (startIndex == testVariable.length) {
return currentIndex == 0
}
// Base case3
if (currentIndex < 0) { // A closing parenthesis did not find its corresponding opening parenthesis
return false
}
// Recursive case1
if (testVariable[startIndex] == "(") {
return balanced(testVariable, startIndex + 1, currentIndex + 1)
}
// Recursive case2
else if (testVariable[startIndex] == ")") {
return balanced(testVariable, startIndex + 1, currentIndex - 1)
}
else {
return false // the string contained an unrecognized character
}
}
// Driver Code
testVariable = ["(", "(", ")", ")", "(", ")"]
console.log("The array [\"(\", \"(\", \")\", \")\", \"(\", \")\"] is balanced: " + balanced(testVariable))
testVariable = ["(", "(", ")"]
console.log("The array [\"(\", \"(\", \")\"] is balanced: " + balanced(testVariable))

Explanation

Our task is to ...