DSAbeginner 7 min
First in, first out. Enqueue and dequeue, and see how a queue differs from a stack.
What a queue is, its main operations, and when to use one instead of a stack.
Whenever work must be handled in the order it arrived, you need a queue: print jobs, customer support tickets, tasks waiting for a worker, and the breadth-first search algorithm you will meet later.
A queue follows FIFO: First In, First Out. The item that has waited longest leaves first.
x to the back.A well-built queue does each of these in O(1).
Press play to see people join the line and get served in order.
(empty)
An empty queue. First in, first out.
front shows Asha, who is next in line.dequeue removes Asha, who joined first.Simulate a printer: enqueue three job names, then dequeue and print each one in order.
length first.shift is free. It is O(n) for arrays.You finished the DSA beginner section. Next: linked lists, sorting, searching and trees.
const queue = [];
queue.push("Asha"); // enqueue
queue.push("Ravi");
queue.push("Zoya");
console.log(queue); // [ 'Asha', 'Ravi', 'Zoya' ]
console.log(queue.shift()); // Asha (dequeue)
console.log(queue[0]); // Ravi (front)
console.log(queue); // [ 'Ravi', 'Zoya' ]