![]() |
VOOZH | about |
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, ”}”, ”(“, ”)”, ”[“, ”]” are correct in exp.
Examples:
Input : exp = “[()]{}{[()()]()}”
Output : true
Input : exp = “[(])”
Output : false
We have discussed a stack based solution. Here we are not allowed to use the stack. Looks like this problem cannot be solved without extra space (please see comments at the end). We use recursion to solve the problem.
Follow the steps below to solve the problem:
Below is the implementation of the above algorithm:
Not Balanced
Time Complexity:
The given implementation of the balanced parenthesis check algorithm uses recursion. For each recursive call, we iterate over the input expression once. Thus, the time complexity can be expressed as O(n^2), where n is the length of the input expression.
Space Complexity:
The algorithm uses recursion, which creates a new stack frame for each recursive call. The space occupied by the stack frames is proportional to the maximum depth of the recursion tree. The maximum depth of the recursion tree in the worst case is n/2, where n is the length of the input expression. Therefore, the space complexity of the algorithm can be expressed as O(n).
The above solution is very inefficient compared to the stack-based solution. This seems to only useful for recursion practice problems.