Microsoft Interview Question

Design an algorithm for parsing code to check whether all the brackets and parentheses match.

Interview Answers

Anonymous

Feb 14, 2016

For just parentheses, maintain a counter that increments when an opening bracket is encountered and decrements when a closing bracket is encountered. At the end, if the count = 0, all parentheses match, if count > 0 there are too many opening parentheses, and too few if count < 0.

1

Anonymous

Aug 14, 2016

For both parantheses and brackets (and whetever else): you can use a stack. Go through the input and add to the top of the stack every opening brackets/parantheses you find, and for every closing ones you find, compare it with the current element at the top of the stack. If they match, keep going. If they don't, stop and output "doesn't match" message. If you reached the end of the input, check the size of the stack. If it's 0, all parantheses/brackets were match and output "match" message. If there are elements left in the stack, some opening parantheses were never matched so output "doesn't match" message.