Problem
Given a string containing only round, square and curly brackets, decide whether it is valid: every opening bracket must be closed by the same type of bracket, in the correct order.
Approach
Use a stack. Push each opening bracket. For each closing bracket, the top of the stack must be the matching opening bracket; pop it if so, and fail otherwise.
The string is valid only if the stack is empty at the end, which catches opening brackets that were never closed.
The solution files below implement this approach in C++, Python and TypeScript.
Complexity
- Time: O(n).
- Space: O(n) for the stack.
Edge cases
- A closing bracket with an empty stack is invalid.
- An odd-length string can never be valid, which allows an early exit.
- Correct counts in the wrong order, such as a round bracket closed by a square one, are invalid.