← Back

Queue

FIFOsequentialscheduling
Press play to start
1class Queue<T> {
2 private items: T[] = []
3 enqueue(item: T): void { this.items.push(item) }
4 dequeue(): T | undefined { return this.items.shift() }
5 peek(): T | undefined { return this.items[0] }
6 isEmpty(): boolean { return this.items.length === 0 }
7 size(): number { return this.items.length }
8}
9const q = new Queue<number>()
10q.enqueue(10); q.enqueue(20); q.enqueue(30)
11q.peek() // 10 (front)
12q.dequeue() // 10
Step 1/0

Complexity

Best:O(1)
Average:O(1)
Worst:O(1)
Space:O(n)

Description

A First-In-First-Out (FIFO) data structure. Elements are added at the rear and removed from the front.

When to use

Task scheduling, BFS, print spoolers, messaging systems, and any scenario requiring ordered processing.