JS Built-ins
Algorithmsbeginner

Stack: Push and Pop

πŸ“– Usage Example
const stack = [];
stack.push(1); stack.push(2);
stack.pop(); // 2 β€” last in, first out

A stack uses push/pop for LIFO (Last In, First Out) behavior.

Stack Data Structure

A Stack is a Last-In-First-Out (LIFO) data structure where elements are added and removed from the same end (the top).

Operations:

  • push(x): Add element x to the top
  • pop(): Remove and return the top element
  • peek(): View the top element without removing
  • size: Number of elements

Real-world example: Browser back button (most recent page visited is removed first).

class Stack {
  push(x: any): void {}
  pop(): any {}
  peek(): any {}
  get size(): number {}
}

const s = new Stack()
s.push(1)
s.push(2)
s.pop() // 2
πŸ’‘ Hints (5)
  • β€’ Use an array internally to store elements.
  • β€’ push() should append to the end.
  • β€’ pop() should remove and return the last element.
  • β€’ peek() should return the last element without removing.
  • β€’ size should return the array length.