Introduction to Practice Problems

Welcome to the practical segment of our JavaScript programming journey! Today, we're applying the knowledge from past lessons to solve two practice problems using advanced JavaScript data structures: queues, deques, and binary search trees with custom class keys.

First Practice Problem: Implementing Queues with Deques

Consider an event-driven system, like a restaurant. Orders arrive, and they must be handled in the order they were received, following the First In, First Out (FIFO) principle. This principle makes it a perfect scenario for a queue or deque implementation in JavaScript.

class Queue {
    constructor() {
        // Initializing an empty queue
        this.buffer = [];
    }

    // Adding (enqueueing) an item to the queue
    enqueue(val) {
        this.buffer.unshift(val);
    }

    // Removing (dequeuing) an item from the queue
    dequeue() {
        return this.buffer.pop();
    }

    // Checking if the queue is empty
    isEmpty() {
        return this.buffer.length === 0;
    }

    // Checking the size (number of items) in the queue
    size() {
        return this.buffer.length;
    }
}

// Example usage:
const queue = new Queue();
queue.enqueue('order1');
queue.enqueue('order2');
console.log(queue.dequeue()); // Outputs 'order1'
console.log(queue.isEmpty()); // Outputs false
console.log(queue.size());    // Outputs 1

This code demonstrates the creation and operation of a Queue class, which leverages JavaScript arrays to efficiently implement a queue. The Queue class includes methods to enqueue (add) an item, dequeue (remove) an item, check if the queue is empty, and return the queue's size. Enqueue operations add an item to the beginning of the array (simulating the arrival of a new order), while dequeue operations remove an item from the end (simulating the serving of an order), maintaining the First In, First Out (FIFO) principle.

Analyzing the First Problem Solution

We've mimicked a real-world system by implementing a queue using JavaScript arrays. The enqueuing of an item taps into the FIFO principle, similar to the action of receiving a new order at the restaurant. The dequeuing serves an order, reflecting the preparation and delivery of the order.

Second Practice Problem: Using Binary Search Trees for a Leaderboard
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal