Stacks: Valid Brackets
A stack is last in, first out. In Python, a list is a stack: append to
push and pop to take the top, both O(1).
The signal: things that nest. Brackets, HTML tags, undo history, and evaluating expressions all need "the most recent unfinished thing".
To check brackets, push each opener. On a closer, the top of the stack must be the matching opener, so pop it and compare. At the end the stack must be empty. One pass, O(n) time and O(n) space.
Two common mistakes: popping from an empty stack (a string that starts with
)), and forgetting the final check, so "((" passes.
A slow version keeps calling s.replace("()", "") until nothing changes.
Each call scans the whole string, so deep nesting makes it O(n²).
Exercise: finish is_valid so it returns True when every bracket in
s (made only of ()[]{}) is closed by the right kind in the right order.
Press Check to run the tests.