Related Articles
Data Structures | Misc | Question 4
• Last Updated : 22 Feb, 2013

The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)

(A) queue
(B) stack
(C) tree
(D) list

Answer: (B)

Explanation: There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types.

 `void` `func(``int` `c, ``int` `a[])``{``   ``return`  `((c +2)  + arr[(c-2)]) ; ``}`

Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same.

 `/*Return 1 if expression has balanced parentheses */``bool` `areParenthesesBalanced(expression )``{ ``   ``for` `each character in expression``   ``{``      ``if``(character == ’(’ || character == ’{’ || character == ’[’) ``        ``push(stack, character);``      ``if``(character == ’)’ || character == ’}’ || character == ’]’) ``      ``{``         ``if``(isEmpty(stack))  ``           ``return` `0; ``/*We are seeing a right parenthesis  ``                       ``without a left pair*/`` ` `         ``/* Pop the top element from stack, if it is not a pair``             ``bracket of character then there is a mismatch. ``             ``This will happen for expressions like {(}) */``         ``else` `if` `(! isMatchingPair(pop(stack), character) ) ``           ``return` `0;   ``      ``}``   ``}``   ` `   ``if``(isEmpty(stack))``     ``return` `1; ``/*balanced*/``   ``else`  `     ``return` `0;  ``/*not balanced*/`   `} ``/* End of function to check parentheses */`` ` `/* Returns 1 if character1 and character2 are matching left``   ``and right parentheses */``bool` `isMatchingPair(character1, character2)``{``   ``if``(character1 == ‘(‘ && character2 == ‘)’)``     ``return` `1;``   ``else` `If(character1 == ‘{‘ && character2 == ‘}’)``     ``return` `1;``   ``else` `If(character1 == ‘[‘ && character2 == ‘]’)``     ``return` `1;``   ``else` `     ``return` `0;``}`

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up