Solution Review: Balance Parenthesis
This review provides a detailed analysis of the solution to determine whether or not an array contains balanced parenthesis.
We'll cover the following...
Solution: Using Recursion
Press + to interact
def balanced(testVariable, startIndex = 0, currentIndex = 0) :# Base case1 and 2if startIndex == len(testVariable) :return currentIndex == 0# Base case3if currentIndex < 0 : # A closing bracket did not find its corresponding opening bracketreturn False# Recursive case1if testVariable[startIndex] == "(" :return balanced(testVariable, startIndex + 1, currentIndex + 1)# Recursive case2elif testVariable[startIndex] == ")" :return balanced(testVariable, startIndex + 1, currentIndex - 1)# Driver CodetestVariable = ["(", "(", ")", ")", "(", ")"]print(balanced(testVariable))
Explanation
Our task is to read an array of parentheses from left to right and decide whether the symbols are balanced.
To solve this problem, notice that the most recent opening ...
Access this course and 1400+ top-rated courses and projects.