IT238 Data Structure and Algorithms

Data Structure and AlgorithmsUnit 511 min read

Queues, Priority Queues, and Real-World Scheduling

Unit 5 of Data Structure and Algorithms covers queues (FIFO, circular, deque), priority queues (min-heap, max-heap), their operations (enqueue, dequeue, peek), time complexity, and applications in scheduling, task management, and resource allocation—with traces, code, and real-world ties to eSewa, Daraz, and Ncell.

Core Concepts

Queues: First-In-First-Out (FIFO) Order

A queue is a linear data structure that follows the FIFO (First-In-First-Out) principle. Elements are added at the rear (enqueue) and removed from the front (dequeue). It is analogous to a real-world queue (line), where the first person to join is the first to be served.

Key Operations:

  • Enqueue: Add an element to the rear.
  • Dequeue: Remove an element from the front.
  • Peek/Front: View the front element without removal.
  • isEmpty: Check if the queue is empty.
  • isFull: Check if the queue is full (for fixed-size implementations).

Time Complexity:

Operation Time Complexity
Enqueue O(1)
Dequeue O(1)
Peek O(1)

Types of Queues:

  1. Simple Queue: Basic FIFO implementation.
  2. Circular Queue: Efficiently reuses space by wrapping around.
  3. Double-Ended Queue (Deque): Allows insertion and deletion from both ends.
XYZFRONTREARoutin
Double-Ended Queue (Deque): Insert/Delete at both ends
ABCFRONTREARoutin
Circular Queue: Reuses space by wrapping around (front=rear=3)

ABCFRONTREARoutin
Simple Queue: FIFO order (Enqueue at rear, Dequeue at front)

Example: Circular Queue

A circular queue avoids wasting space by using a fixed-size array and reusing slots after the rear reaches the end.

Code (Circular Queue in C):

#include <stdio.h>
#define MAX 5

int queue[MAX];
int front = -1, rear = -1;

void enqueue(int x) {
    if ((front == 0 && rear == MAX - 1) || (rear == front - 1)) {
        printf("Queue is full\n");
    } else if (front == -1) {
        front = rear = 0;
        queue[rear] = x;
    } else if (rear == MAX - 1) {
        rear = 0;
        queue[rear] = x;
    } else {
        rear++;
        queue[rear] = x;
    }
}

int dequeue() {
    int item;
    if (front == -1) {
        printf("Queue is empty\n");
        return -1;
    }
    item = queue[front];
    if (front == rear) {
        front = rear = -1;
    } else if (front == MAX - 1) {
        front = 0;
    } else {
        front++;
    }
    return item;
}

Trace: Enqueue and Dequeue Operations

Step Operation Front Rear Queue State (Array)
1 Enqueue(10) 0 0 [10, -, -, -, -]
2 Enqueue(20) 0 1 [10, 20, -, -, -]
3 Enqueue(30) 0 2 [10, 20, 30, -, -]
4 Dequeue() 1 2 [-, 20, 30, -, -]
5 Enqueue(40) 1 3 [-, 20, 30, 40, -]
6 Dequeue() 2 3 [-, -, 30, 40, -]
7 Enqueue(50) 2 4 [-, -, 30, 40, 50]
8 Dequeue() 3 4 [-, -, -, 40, 50]
9 Enqueue(60) 3 0 [60, -, -, 40, 50]


Priority Queues: Order Matters

A priority queue is a specialized queue where elements are dequeued based on their priority, not arrival order. It is implemented using:

  • Min-Heap: Smallest element has highest priority.
  • Max-Heap: Largest element has highest priority.

Key Operations:

  • Insert: Add an element with a priority.
  • Extract-Min/Max: Remove the highest-priority element.
  • Peek: View the highest-priority element.

Time Complexity:

Operation Time Complexity (Heap)
Insert O(log n)
Extract O(log n)
Peek O(1)

Example: Min-Heap Priority Queue

A min-heap ensures the smallest element is always at the root.

Code (Min-Heap in Python):

import heapq

class PriorityQueue:
    def __init__(self):
        self.heap = []

    def enqueue(self, item, priority):
        heapq.heappush(self.heap, (priority, item))

    def dequeue(self):
        return heapq.heappop(self.heap)[1]

    def peek(self):
        return self.heap[0][1] if self.heap else None

    def is_empty(self):
        return len(self.heap) == 0

Trace: Insert and Extract Operations

Step Operation Heap State (Priority, Item) Peek
1 Enqueue(10, 3) [(3, 10)] 10
2 Enqueue(20, 1) [(1, 20), (3, 10)] 20
3 Enqueue(30, 2) [(1, 20), (2, 30), (3, 10)] 20
4 Dequeue() [(2, 30), (3, 10)] 30
5 Enqueue(40, 0) [(0, 40), (2, 30), (3, 10)] 40
6 Dequeue() [(2, 30), (3, 10)] 30

403050102060
Min-Heap Priority Queue: Root (40) has highest priority (smallest value)

In the Real World

  1. eSewa and Khalti Transactions:

    • Queue Idea: When multiple users request bill payments simultaneously, eSewa processes them in FIFO order to ensure fairness. If two users pay their electricity bill at the same time, the one who initiated the request first gets processed first.
    • Priority Queue Idea: For premium users (e.g., those with higher transaction limits), Khalti may use a priority queue to process their transactions before others, ensuring faster service.
  2. Daraz Order Fulfillment:

    • Queue Idea: When a customer places an order on Daraz, the system assigns it to a warehouse worker in FIFO order. The first order received is the first to be packed and shipped.
    • Priority Queue Idea: If a customer selects "Express Delivery," their order is placed in a high-priority queue, ensuring it is processed before standard orders.
  3. Ncell Call Center:

    • Priority Queue Idea: Incoming customer calls are routed based on priority. Complaints about network issues are given higher priority (min-heap) and resolved before routine inquiries, reducing customer dissatisfaction.
  4. Bank Loan Processing:

    • Priority Queue Idea: Banks use priority queues to process loan applications. Applications from high-net-worth individuals or those with lower risk scores (min-heap for risk) are processed first, optimizing resource allocation.
  5. NEPSE Stock Trading:

    • Queue Idea: Buy/sell orders for stocks are executed in FIFO order for the same price. If two traders place a buy order for 100 shares of Nabil Bank at Rs. 500, the first order is fulfilled before the second.
    • Priority Queue Idea: Market makers or institutional investors may get priority execution (higher priority in the queue) for large trades to ensure liquidity.
  6. Pathao Driver Assignment:

    • Priority Queue Idea: When multiple drivers are available for a ride request, Pathao assigns the driver closest to the pickup location (highest priority) first. This is implemented using a max-heap where the driver with the smallest distance (highest priority) is dequeued first.

Applications of Queues and Priority Queues

Data Structure Applications Example Systems
Queue Task scheduling, printer spooling Operating systems, Daraz orders
Priority Queue CPU scheduling, real-time systems Ncell call centers, eSewa payments
Deque Undo/redo operations, palindromes Text editors, browser history

Comparison: Queue vs. Priority Queue

Feature Queue Priority Queue
Order FIFO Priority-based
Implementation Linked List or Array Heap (Min or Max)
Use Case Fair resource allocation Urgent task handling
Time for Insert O(1) O(log n)
Time for Remove O(1) O(log n)

Worked Example: Bank Loan Processing with Priority Queue

Scenario: A bank receives loan applications with different risk levels (1 = lowest risk, 5 = highest risk). The bank wants to process low-risk applications first.

Priority Queue Operations:

  1. Enqueue applications with their risk levels:

    • (Risk 3, Customer A)
    • (Risk 1, Customer B)
    • (Risk 5, Customer C)
    • (Risk 2, Customer D)
  2. Process applications in order of increasing risk (min-heap).

Trace:

Step Operation Heap State (Risk, Customer) Processed Customer
1 Enqueue(3, A) [(3, A)] -
2 Enqueue(1, B) [(1, B), (3, A)] -
3 Enqueue(5, C) [(1, B), (3, A), (5, C)] -
4 Enqueue(2, D) [(1, B), (2, D), (3, A), (5, C)] -
5 Dequeue() [(2, D), (3, A), (5, C)] Customer B
6 Dequeue() [(3, A), (5, C)] Customer D
7 Dequeue() [(5, C)] Customer A
8 Dequeue() [] Customer C

Visualization:

0B1D2A3C4
Bank Loan Processing: Priority Queue steps (priority, customer)

Exam Tip

  1. Understand FIFO vs. Priority:

    • Queues are strictly FIFO; priority queues ignore order for priority.
    • Common Mistake: Confusing a queue with a stack (LIFO). Always emphasize FIFO.
  2. Circular Queue Implementation:

    • Key Insight: Use modulo arithmetic ((rear + 1) % MAX) to wrap around.
    • Exam Question: Given a circular queue, trace the front and rear pointers after a series of enqueue/dequeue operations.
  3. Heap Operations:

    • Heapify Up/Down: After insertion or deletion, the heap property must be restored.
    • Code Snippet: Be ready to write a function to insert into a min-heap or extract the min element.
  4. Real-World Scenarios:

    • Application Questions: Expect questions like:
      • "How would you implement a call center system using queues?"
      • "Why might a bank use a priority queue for loan processing?"
    • Answer Tip: Relate to fairness (FIFO) or urgency (priority).
  5. Time Complexity:

    • Queue: All operations are O(1).
    • Priority Queue (Heap): Insert and extract are O(log n).
    • Common Pitfall: Assuming a priority queue is O(1) like a queue.
  6. Edge Cases:

    • Empty Queue: Handle front == -1 in circular queues.
    • Full Queue: Check (rear + 1) % MAX == front for circular queues.
    • Priority Queue: What if two elements have the same priority? (Use secondary keys like arrival time.)
  7. Pseudocode is Key:

    • Exam Format: Often, you’ll be asked to write pseudocode for enqueue/dequeue in a circular queue or heap operations. Practice tracing step-by-step.

Based on the TU BIM syllabus for Data Structure and Algorithms (IT238), unit 5.

Discussion

Loading…