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.
Think of the plate stack dispenser in a university cafeteria:
| 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)$ |
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid:
(, {, [), push its corresponding closing bracket onto the stack.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 [] → Valid Parentheses (True)!
push() and pop() operations on a properly implemented Stack?pop() on an empty stack results in a "Stack Underflow"?({[]})?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.