Array & Data-Structure Operations
Stack Push and Pop
A stack is Last-In-First-Out (LIFO): push adds to the top, pop removes from the top. A fixed capacity shows overflow (push when full) and underflow (pop when empty).
1Detailed explanation
A stack only allows access to its top. push puts a value on top; pop removes the top value. The last value pushed is the first popped — LIFO.
Both operations are O(1). With a fixed capacity, pushing onto a full stack is an overflow and popping an empty stack is an underflow; real programs must handle both (exceptions, return codes or a growing array).
Stacks power function calls (the call stack), undo history, expression evaluation and depth-first search.
2Pseudocode
procedure push(S, value)
if size(S) = capacity
report overflow; return
S.items.append(value)
procedure pop(S)
if size(S) = 0
report underflow; return null
return S.items.removeLast()3Interactive visualization
Size 0 / 3 · LIFO — the last value pushed is the first one popped
A stack is Last-In-First-Out (LIFO): push adds to the top, pop removes from the top. A fixed capacity shows overflow (push when full) and underflow (pop when empty).
4Implementations
Equivalent implementations in four languages — the same code the visualizer highlights line by line. Each is a complete program.
class Stack {
constructor(capacity) {
this.items = [];
this.capacity = capacity;
}
push(value) {
if (this.items.length === this.capacity) {
console.log("Stack Overflow: cannot push " + value);
return;
}
this.items.push(value);
}
pop() {
if (this.items.length === 0) {
console.log("Stack Underflow: nothing to pop");
return null;
}
return this.items.pop();
}
}
const stack = new Stack(3);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
console.log("Popped:", stack.pop());
console.log("Popped:", stack.pop());
console.log("Popped:", stack.pop());
console.log("Popped:", stack.pop());
console.log("Final stack (bottom -> top):", stack.items);
5Time and space complexity
Time: push and pop only touch the top element, so each operation is O(1). (Dynamic arrays occasionally resize on push, which is O(n) for that call but O(1) amortized.) A sequence of k operations costs O(k).
Space: Each operation uses O(1) extra space; the stack itself stores up to capacity elements → O(n).
6Common interview variations
- Valid parentheses.
- Min stack (get the minimum in O(1)).
- Evaluate reverse Polish notation.
- Implement a queue using two stacks.
- Next greater element (monotonic stack).