Back to DSA Topics

Stacks

Stacks follow LIFO (Last In First Out) principle. Elements are added and removed from the top.

Animated Visualization

Step 1 of 5
Top
30
20
10
Base
Initial stack: [10, 20, 30] - Top: 30, Base: 10
javascript
← Scroll →
// Stack Implementation using Array
class Stack {
constructor() {
this.items = [];
}
// Push element onto stack
push(element) {
this.items.push(element);
}
// Pop element from stack
pop() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items.pop();
}
// Peek at top element
peek() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items[this.items.length - 1];
}
// Check if stack is empty
isEmpty() {
return this.items.length === 0;
}
// Get stack size
size() {
return this.items.length;
}
// Time Complexity:
// Push: O(1)
// Pop: O(1)
// Peek: O(1)
// Search: O(n)
Swipe horizontally to view full code

Explanation

Stacks are linear data structures that follow the LIFO principle. They're used in expression evaluation, function call management, and undo operations. All main operations (push, pop, peek) are O(1).

Operations & Complexity

PushO(1)

Add element to top

PopO(1)

Remove element from top

PeekO(1)

View top element

SearchO(n)

Must traverse stack

Time Complexity

PushO(1)

Add element to top

PopO(1)

Remove element from top

PeekO(1)

View top element

SearchO(n)

Must traverse stack