A stack remembers what is still open, and the most recent one must close first.
A stack is like a pile of plates: you can only add to the top and only take from the top (last in, first out). To check brackets, walk through the text. Each opening bracket goes on the pile. Each closing bracket must match the plate on top, and then that plate is removed. If the closer does not match (or the pile is empty), the text is invalid. At the end the pile must be empty.
{[()]}, then {[(])}. Where exactly does the second one fail?(((. Every char is fine, so why is it invalid? Look at the stack at the end.) alone. What does the code check before looking at the top?()[]{}. How tall does the stack ever get?((( never fails inside the loop. The final len(stack) == 0 check matters.[(]) from [()].Time: O(n) – each character is pushed or popped once. Space: O(n) in the worst case (all opening brackets).