Use a stack to validate that every opening bracket has a correct matching close.
Use a stack to verify that every opening bracket has a matching closing bracket in the correct order. Scan left-to-right: push openers, pop when a closer matches the top; any mismatch or leftover items mean the string is invalid.
Iterate through each character. Push opening brackets ( [ { onto the stack. When you see a closing bracket, check whether the top of the stack is the matching opener. Pop on a match; otherwise the string is invalid.
For the string "([{}])": push (, push [, push {, then } matches { so pop, ] matches [ so pop, ) matches ( so pop. Stack is empty → valid.
One pass through the string with at most one push/pop per character, so O(n) time. The stack holds at most n/2 openers at once, so O(n) space.
This algorithm is used in compilers, linters, and code editors to validate expression syntax. It extends naturally to any paired-delimiter problem (XML tags, HTML, markdown fences).