Collection Kit

PriorityQueue

Linear

A PriorityQueue is a data structure that stores elements along with their priorities, allowing for efficient retrieval of the highest (or lowest) priority element.

Import Statement
import { PriorityQueue } from "collection-kit";

Key Features

  • Priority-Based Ordering: Elements are ordered based on their priority rather than their insertion order.
  • Dynamic Size: Can grow and shrink as elements are added or removed.

Common Operations

Enqueue
Add an element with a specified priority.
Dequeue
Remove and return the element with the highest priority.
Peek
Return the highest priority element without removing it.
Size
Return the number of elements in the priority queue.

Example Code

import { PriorityQueue } from "collection-kit";

const pq = new PriorityQueue();
pq.enqueue(10, 2);  // value, priority
pq.enqueue(20, 1);
pq.enqueue(30, 3);

console.log("Highest priority:", pq.peek()); // 30
console.log("Dequeued:", pq.dequeue());      // 30
console.log("Size:", pq.size());             // 2