🌇DSA
← Back
Data StructureBeginner
📚

Stacks

Last In First Out structure

⏱️ 3–4 hours🧩 10 LeetCode
🔒 Login to unlock solutions and track progress. Login

What is it?

A stack works like a pile of plates — you can only add or remove from the top. This is called LIFO (Last In, First Out).

  • Push → place a plate on top
  • Pop → remove the top plate
  • Peek → look at the top plate without removing it

Real-World Examples

Browser back button
Undo / Redo in editors
Bracket matching
Calculator expressions
Function call stack
Backtracking in games

Code Example

What this code shows

Push 1, 2, then 3 onto the stack. Peek shows 3 is on top — without removing it. Pop removes 3. The stack now holds [1, 2].

const stack = [];

stack.push(1); // stack: [1]
stack.push(2); // stack: [1, 2]
stack.push(3); // stack: [1, 2, 3]

console.log("Peek:", stack.at(-1)); // look at top → 3 (not removed)
console.log("Popped:", stack.pop()); // remove top  → 3
console.log("Stack now:", stack);    // remaining   → [1, 2]

Expected Output

Peek: 3
Popped: 3
Stack now: [1, 2]

LeetCode Practice