Validate a string of brackets like "([]{})". Data structure?
Options
- Queue
- Stack (Correct option)
- Heap
- Trie
Answer
Stack
Why
A stack is last-in, first-out, like a pile of plates.
Walk through the string: push every opening bracket. On a closing bracket, the top of the stack must be its matching opener; pop it. If it doesn't match, or the stack is empty, the string is invalid.
At the end the stack must be empty. O(n).
Remember
Matching pairs / nesting → stack.