Suppose you are given an arithmetic expression. How will you check whether it has balanced parentheses or not?
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:
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. |