### Check whether an arithmetic expression has balanced parentheses stack stackqueuelinkedlist    Posted: 4 years ago Edit answers (1) views (4330)

Suppose you are given an arithmetic expression. How will you check whether it has balanced parentheses or not?

 Posted: 4 years ago Updated: 4 years ago 0 0 Edit An arithmetic expression with balanced parentheses will have left and right parentheses in order. Since stack is implemented using LIFO (last in - first out), we can compare the last inserted parentheses in the stack with the current one and check whether they are a pair or not. The algorithm works as follows: Convert the arithmetic expression into a character array. PUSH the left parentheses into the stack. For right parentheses check the status of the stack. If the stack is empty, then the right parentheses has no left pair and return false (not balanced). If the stack is not empty, POP the stack and match it with the right parentheses. If they do not match, return false (not balanced). At the end check the status of the stack. If it is empty, return true (balanced), otherwise false (not balanced). Example - For an arithmetic expression like  } ([ ... ])', the algorithm will return false since no left pair of the first  } ' is found. For an arithmetic expression like [{ ( ... }]', the algorithm will return false since the }' does not match with  ( '.Time complexity = O(n) where n is the length of the arithmetic expression. public boolean isExpressionBalanced(char[] expression){ /* Create a new stack */ Stack myStack = new Stack(); /* For each character in the array */ for(int i=0;i