🚃Queue

What is Queue?

💡 A Queue is a data structure that follows the First-In-First-Out (FIFO) principle. Imagine a line at a coffee shop - the first person who enters the line is the first one served. This "queue" behavior governs how data is added and removed in a queue data structure. A queue is typically implemented with a doubly linked list.

Here are some key characteristics of queues:

  • Limited access: You can only add elements to the back (called the rear) and remove them from the front (called the head).

  • FIFO order: The element added first is the first one to be removed. This is like the coffee shop line where the person who entered first gets served first, before anyone who arrives later.

  • Dynamic size: Queues can grow or shrink as needed by adding or removing elements.

  • Efficient enqueue/dequeue operations: Adding (enqueuing) or removing (dequeuing) elements from the front and back are typically constant-time operations (O(1)O(1)).

Big O Notation of Queue Operations

OperationTime ComplexityExplanation

Enqueue

O(1)O(1)

Adding an element to the back is fast.

Dequeue

O(1)O(1)

Removing the front element is fast.

Peek

O(1)O(1)

Accessing the front element is fast.

Search

O(n)O(n)

Finding a specific element requires traversing the queue.

IsEmpty

O(1)O(1)

Checking if the queue is empty is fast.

Overall, queues are versatile data structures with efficient access for both ends. They ensure fair and orderly processing of data or tasks in the order they arrive. However, similar to stacks, accessing specific elements within the queue or searching for them is less efficient than in other data structures.

How are queues used?

Common use cases of queues include:

  • Task scheduling: In operating systems, queues are used to manage processes waiting for CPU time or other resources.

  • Data buffering: Queues can be used to buffer data streams, allowing for smooth transfer even if the receiving end isn't always ready.

  • Message passing: Queues are used in communication systems to store messages sent between different parts of a system, ensuring they are received in the correct order.

  • Job processing: Queues can be used to manage jobs waiting to be processed by a system, ensuring they are handled in the order they arrived.

Implementation of Queue In JavaScript

// Working in progress

Last updated