27: Check for balanced parentheses using a stack.
⏳⌚ 00:00:00

Question:-

Check for balanced parentheses using a stack.
Example 1:
Input: exp = “[()]{}{[()()]()}”
Output: Balanced
Explanation: all the brackets are well-formed
Example 2:
Input: exp = “[(])”
Output: Not Balanced
Explanation: 1 and 4 brackets are not balanced because there is a closing ‘]’ before the closing ‘(‘

Steps to solve:-

1. areBracketsBalanced function:-
The areBracketsBalanced function takes a string expr as input and returns a boolean value to indicate whether the brackets are balanced or not.
Inside the areBracketsBalanced function:
A stack char called temp is declared to hold the previous brackets. A for loop iterates through each character in the input expr.
Within the loop:-
If the stack is empty, the code pushes the current character onto the stack, assuming it is an opening bracket.
If the stack is not empty, it checks whether the current character forms a complete pair with the top character on the stack. If it does, it pops the opening bracket from the stack, indicating that the pair is balanced.
If the current character is neither an opening bracket nor forms a balanced pair with the top of the stack, it is pushed onto the stack.
After processing all characters in the input string, if the stack is empty, it means that all brackets are balanced. The function returns true. Otherwise, it returns false.
2. In the main function:- A test expression expr (e.g., "{()}[]") is declared.
The areBracketsBalanced function is called with the test expression.
Depending on the result, "Balanced" or "Not Balanced" is printed.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(1)