Stacks: LIFO Operations, Array/List Implementations & Bracket Matching
Stacks: LIFO Operations, Array/List Implementations & Bracket Matching
A Stack is a linear data structure governed strictly by the LIFO (Last In, First Out) principle. The last element added to the stack is the first element to be removed. Stacks power fundamental computing mechanisms: the browser back-button history, text editor undo/redo, expression evaluation, and compiler function call stacks.
1. Real-World Analogy: The Spring-Loaded Plate Dispenser
Think of the plate stack dispenser in a university cafeteria:
- When a dishwasher adds clean plates, they are placed on the top of the stack (Push).
- When a hungry student takes a plate, they take the plate from the top (Pop).
- You cannot access the plate at the bottom without first removing every plate above it!
2. The Core Stack Operations
| Operation | Action | Time Complexity |
|---|---|---|
push(val) | Adds an element to the top of the stack | $O(1)$ |
pop() | Removes and returns the top element | $O(1)$ |
peek() / top() | Views the top element without removing it | $O(1)$ |
isEmpty() | Checks if the stack contains zero elements | $O(1)$ |
3. Classic Problem: Valid Parentheses & Bracket Matching
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid:
- 1Open brackets must be closed by the same type of brackets.
- 2Open brackets must be closed in the correct order.
The Stack Solution:
- When encountering an opening bracket (
(,{,[), push its corresponding closing bracket onto the stack. - When encountering a closing bracket, pop from the stack. If the popped bracket does not match or the stack is empty, the string is invalid!
- If the stack is empty at the end, all brackets were matched successfully.
4. Multi-Language Implementations: Valid Parentheses
Python 3:
Modern JavaScript / TypeScript:
5. Step-by-Step Trace: s = "{ [ ] ( ) }"
| Char | Type | Stack Before | Action | Stack After | Status |
|---|---|---|---|---|---|
{ | Open | [] | Push { | ['{'] | Valid |
[ | Open | ['{'] | Push [ | ['{', '['] | Valid |
] | Close | ['{', '['] | Pop matches [ | ['{'] | Valid |
( | Open | ['{'] | Push ( | ['{', '('] | Valid |
) | Close | ['{', '('] | Pop matches ( | ['{'] | Valid |
} | Close | ['{'] | Pop matches { | [] | Valid |
End State: Stack is empty [] $\to$ Valid Parentheses (True)!
Multiple Choice Questions
push() and pop() operations on a properly implemented Stack?pop() on an empty stack results in a "Stack Underflow"?({[]})?Monotonic Stacks: Next Greater Element & Histogram Area Patterns
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.