QA
Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?

ā“ Interview Prompt: Explain Stack (LIFO) and Queue (FIFO) semantics, their core operations, time complexities, and real-world use cases.

Stack follows LIFO (Last-In, First-Out) — the most recently added element is removed first.

Queue follows FIFO (First-In, First-Out) — the oldest element is removed first.

Operations (both $O(1)$):

| Structure | Add | Remove | Peek |

|---|---|---|---|

| Stack | push | pop | peek/top |

| Queue | enqueue | dequeue | front |

Real-World Use Cases:

•
Stack: Browser back/forward history, call stack (recursion), undo/redo, balanced parenthesis checking, DFS traversal.
•
Queue: CPU/disk task scheduling, BFS traversal, print spoolers, request queues in web servers.

Code Implementation Example

typescript
// Stack using array
class Stack<T> {
  private data: T[] = [];
  push(val: T) { this.data.push(val); }
  pop(): T | undefined { return this.data.pop(); }
  peek(): T | undefined { return this.data[this.data.length - 1]; }
  isEmpty(): boolean { return this.data.length === 0; }
}

// Queue using array (O(N) dequeue — use doubly linked list for O(1))
class Queue<T> {
  private data: T[] = [];
  enqueue(val: T) { this.data.push(val); }
  dequeue(): T | undefined { return this.data.shift(); }
  front(): T | undefined { return this.data[0]; }
  isEmpty(): boolean { return this.data.length === 0; }
}
šŸ’”Stack (LIFO) and Queue (FIFO) implementations in TypeScript.
šŸŽÆ Interview Key Takeaway

Stacks model LIFO access (DFS, recursion); Queues model FIFO access (BFS, scheduling). Both offer O(1) push/pop/enqueue/dequeue with proper implementations.

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?