I recently had an interview where I was asked to solve a modified version of this question on leetcode. Instead of checking if the string is valid you are supposed to count the minimum number of brackets that need to be removed in order for the string to be valid.
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
We had discussed some possible outcomes, for example:
- "( [ ) ]" should return 2
- "( [ { } ] )" should return 0
- "( [ ] ] )" should return 1
A test case I thought of after the interview:
- "( [ { ] )" should return 1, but my solution returns 5
I solved it using a stack which basically pushes open brackets, pops corresponding closing brackets, and counts unmatched closing brackets, returns size of the stack plus the unmatched closing brackets, and it passed all of these test cases. After the interview I had thought of a case which my code would fail, "( [ { ] )" returns 5 where it should return 1. If I think of a different solution I can come up with something that would return 1 but when you test "( [ ) ]" it returns 0. I can't figure out how to correctly account for both cases.
Any insight would be helpful.