How the valid parentheses check works
Scan the string once. Push every opening bracket. For a closing bracket, the stack must be non-empty and its top must be the matching opener; pop it and carry on. Anything else means the string is invalid. At the end the string is valid only if the stack is empty — anything left over was opened and never closed.
The Python example checks "{[()()]}", which is balanced.
What to watch for when it runs
- The stack is drawn as a stack, growing and shrinking as brackets are pushed and popped.
- It is deepest at the innermost bracket and empties completely by the end.
- Change the input to "{[(])}" in the editor and run it again to see the mismatch caught.
Time and space complexity
- Time
- O(n)
- Space
- O(n)
One pass over the string. In the worst case — all openers — every character is on the stack at once.