Introduction to Practice Problems

Welcome to the practical segment of our Kotlin programming journey! Today, we'll apply the knowledge from past lessons to solve two practice problems using advanced Kotlin data structures: queues, deques, and sorted maps 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 Kotlin.

Kotlin
import java.util.ArrayDeque

class Queue {
    private val buffer = ArrayDeque<String>()

    // Adding (enqueueing) an item to the queue
    fun enqueue(val: String) {
        buffer.addLast(val)
    }

    // Removing (dequeuing) an item from the queue
    fun dequeue(): String {
        if (isEmpty()) {
            throw IllegalStateException("Queue is empty")
        }
        return buffer.removeFirst()
    }

    // Checking if the queue is empty
    fun isEmpty(): Boolean {
        return buffer.isEmpty()
    }

    // Checking the size (number of items) in the queue
    fun size(): Int {
        return buffer.size
    }
}

fun main() {
    val restaurantQueue = Queue()

    restaurantQueue.enqueue("Order 1")
    restaurantQueue.enqueue("Order 2")

    println("Dequeued: ${restaurantQueue.dequeue()}")
    println("Dequeued: ${restaurantQueue.dequeue()}")
}

This code demonstrates the creation and operation of a Queue class, which leverages ArrayDeque 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 end of the deque (simulating the arrival of a new order), while dequeue operations remove an item from the front (simulating the serving of an order), maintaining the First In, First Out (FIFO) principle.

Second Practice Problem: Using Sorted Maps with Custom Class as a Key
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