The Wayback Machine - https://web.archive.org/web/20240818163947/https://www.geeksforgeeks.org/data-structure-for-future-reservations-for-a-single-resource/
Open In App

Data Structure for a single resource reservations

Last Updated : 05 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Design a data structure to do reservations of future jobs on a single machine under following constraints. 

  1. Every job requires exactly k time units of the machine. 
  2. The machine can do only one job at a time.  
  3. Time is part of the system. Future Jobs keep coming at different times. Reservation of a future job is done only if there is no existing reservation within k time frame (after and before) 
  4. Whenever a job finishes (or its reservation time plus k becomes equal to current time), it is removed from system. 

Example:

Let time taken by a job (or k) be = 4

At time 0: Reservation request for a job at time 2 in 
           future comes in, reservation is done as machine 
           will be available (no conflicting reservations)
Reservations {2}

At time 3: Reservation requests at times 15, 7, 20 and 3.
           Job at 7, 15 and 20 can be reserved, but at 3 
           cannot be reserved as it conflicts with a 
           reserved at 2.
Reservations {2, 7, 15, 20}

At time 6: Reservation requests at times 30, 17, 35 and 45
           Jobs at 30, 35 and 45 are reserved, but at 17  
           cannot be reserved as it conflicts with a reserved 
           at 15.
Reservations {7, 15, 30, 35, 45}.
Note that job at 2 is removed as it must be finished by 6.

Let us consider different data structures for this task. One solution is to keep all future reservations sorted in array. Time complexity of checking for conflicts can be done in O(Logn) using Binary Search, but insertions and deletions take O(n) time. Hashing cannot be used here as the search is not exact search, but a search within k time frame. The idea is to use Binary Search Tree to maintain set of reserved jobs. For every reservation request, insert it only when there is no conflicting reservation. While inserting job, do “within k time frame check”. If there is a k distant node on insertion path from root, then reject the reservation request, otherwise do the reservation. 

Implementation:

C++




struct node
{
    int time; // reservation time
    struct node *left, *right;
};
 
// A utility function to create a new BST node
node* newNode(int item)
{
    node* temp = new node;
    temp->time = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
/* BST insert to process a new reservation request at
   a given time (future time).  This function does
   reservation only if there is no existing job within
   k time frame of new job  */
node* insert(node* root, int time, int k)
{
    /* If the tree is empty, return a new node */
    if (root == NULL) return newNode(time);
 
    // Check if this job conflicts with existing
    // reservations
    if ((time-k < root->time) && (time+k > root->time))
        return root;
 
    /* Otherwise, recur down the tree */
    if (time < root->time)
        root->left = insert(root->left, time, k);
    else
        root->right = insert(root->right, time, k);
 
    /* return the (unchanged) node pointer */
    return root;
}


C




// A BST node to store future reservations
struct node
{
    int time; // reservation time
    struct node *left, *right;
};
 
// A utility function to create a new BST node
struct node *newNode(int item)
{
    struct node *temp =
        (struct node *)malloc(sizeof(struct node));
    temp->time = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
/* BST insert to process a new reservation request at
   a given time (future time).  This function does
   reservation only if there is no existing job within
   k time frame of new job  */
struct node* insert(struct node* root, int time, int k)
{
    /* If the tree is empty, return a new node */
    if (root == NULL) return newNode(time);
 
    // Check if this job conflicts with existing
    // reservations
    if ((time-k < root->time) && (time+k > root->time))
        return root;
 
    /* Otherwise, recur down the tree */
    if (time < root->time)
        root->left  = insert(root->left, time, k);
    else
        root->right = insert(root->right, time, k);
 
    /* return the (unchanged) node pointer */
    return root;
}


Java




// A BST node to store future reservations
class Node {
    int time; // reservation time
    Node left, right;
 
    Node(int time)
    {
        super();
        this.time = time;
    }
};
 
// A utility function to create a new BST node
Node newNode(int item)
{
    Node temp = new Node(item);
    return temp;
}
 
/* BST insert to process a new reservation request at
a given time (future time). This function does
reservation only if there is no existing job within
k time frame of new job */
Node insert(Node root, int time, int k)
{
    /* If the tree is empty, return a new node */
    if (root == null)
        return newNode(time);
 
    // Check if this job conflicts with existing
    // reservations
    if ((time - k < root.time) && (time + k > root.time))
        return root;
 
    /* Otherwise, recur down the tree */
    if (time < root.time)
        root.left = insert(root.left, time, k);
    else
        root.right = insert(root.right, time, k);
 
    /* return the (unchanged) node pointer */
    return root;
}
 
// This code is contributed by jainlovely450


Python3




class Node:
    def __init__(self, time):
        self.time = time
        self.left = None
        self.right = None
 
# A utility function to create a new BST node
def newNode(item):
    temp = Node(item)
    return temp
 
""" BST insert to process a new reservation request at
   a given time (future time).  This function does
   reservation only if there is no existing job within
   k time frame of new job  """
def insert(root, time, k):
    """ If the tree is empty, return a new node """
    if root is None:
        return newNode(time)
 
    # Check if this job conflicts with existing
    # reservations
    if (time-k < root.time and time+k > root.time):
        return root
 
    """ Otherwise, recur down the tree """
    if time < root.time:
        root.left = insert(root.left, time, k)
    else:
        root.right = insert(root.right, time, k)
 
    """ return the (unchanged) node pointer """
    return root
 
  # This code is contributed by surajrasr7277


C#




// A BST node to store future reservations
public class Node {
    public int time; // reservation time
    public Node left, right;
 
    public Node(int t)
    {
        time = t;
          left = right = null;
    }
};
 
// A utility function to create a new BST node
Node newNode(int item)
{
    Node temp = new Node(item);
    return temp;
}
 
/* BST insert to process a new reservation request at
a given time (future time). This function does
reservation only if there is no existing job within
k time frame of new job */
Node insert(Node root, int time, int k)
{
    /* If the tree is empty, return a new node */
    if (root == null)
        return newNode(time);
 
    // Check if this job conflicts with existing
    // reservations
    if ((time - k < root.time) && (time + k > root.time))
        return root;
 
    /* Otherwise, recur down the tree */
    if (time < root.time)
        root.left = insert(root.left, time, k);
    else
        root.right = insert(root.right, time, k);
 
    /* return the (unchanged) node pointer */
    return root;
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Javascript




// JavaScript program for the above approach
class node{
    constructor(item){
        this.time = data;
        this.left = null;
        this.right = null;
    }
}
 
// a utility function to create a new BST node
function newNode(item){
    return new node(item);
}
 
/* BST insert to process a new reservation request at
   a given time (future time).  This function does
   reservation only if there is no existing job within
   k time frame of new job  */
function insert(root, time, k){
    // if the tree is empty, return a new node
    if(root == null) return newNode(time);
     
    // check if this job confilicts with existing
    // reservations
    if((time-k < root.time) && (time+k > root.time)){
        return root;
    }
     
    // otherwise, recur down the tree
    if(time < root.time)
        root.left = insert(root.left, time, k);
    else
        root.right = insert(root.right, time, k);
     
    // return the unchanged node pointer
    return root;
}
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Time complexity: O(h), where h is the height of the tree.
Space complexity: O(h) for recursive call stack.

Deletion of job is simple BST delete operation. A normal BST takes O(h) time for insert and delete operations. We can use self-balancing binary search trees like AVL, Red-Black, .. to do both operations in O(Log n) time. 
This question is adopted from this MIT lecture.



Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size.
4 min read
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 min read
Applications of Queue Data Structure
Introduction : A queue is a linear data structure that follows the "first-in, first-out" (FIFO) principle. It is a collection of elements that supports two primary operations - enqueue and dequeue. In the enqueue operation, an element is added to the back of the queue, while in the dequeue operation, an element is removed from the front of the queu
5 min read
A data structure for n elements and O(1) operations
Propose a data structure for the following: The data structure would hold elements from 0 to n-1. There is no order on the elements (no ascending/descending order requirement) The complexity of the operations should be as follows: Insertion of an element – O(1) Deletion of an element – O(1) Finding an element – O(1) We strongly recommend to minimiz
4 min read
Tango Tree Data Structure
INTRODUCTION:' Tango Tree is a data structure for efficient dynamic connectivity and range minimum/maximum query on a set of elements. It is a type of balanced binary search tree that uses finger trees as the underlying data structure to achieve fast and efficient operations. The Tango Tree is designed to support both fast insertions and deletions
4 min read
Applications of Graph Data Structure
A graph is a non-linear data structure, which consists of vertices(or nodes) connected by edges(or arcs) where edges may be directed or undirected. In Computer science graphs are used to represent the flow of computation.Google maps uses graphs for building transportation systems, where intersection of two(or more) roads are considered to be a vert
3 min read
Which data structure is used by Map?
What is a Map? Before learning the data structure used by a map, let us have an overlook of map. Map is the part of the STL library that stores key value pairs in it and no two values have the same keys but the different keys can store similar values. The map stores keys in sorted order. These are some functions which map uses with their Time Compl
2 min read
Applications of linked list data structure
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Applications of linked list in computer science:Implementation of stacks and queuesImplementation of graphs: Adjacency list representation of graphs is th
5 min read
Top 50 Problems on Heap Data Structure asked in SDE Interviews
A Heap is a special Tree-based Data Structure in which the tree is a complete binary tree. Generally, heaps are of two types: Max-Heap and Min-Heap. To know more about this Data Structure in-depth refer to the Tutorial on Heap Data-Structure. Given below are the most frequently asked interview questions on Heaps:  Easy Interview Questions on Heap D
2 min read
Remove duplicates from unsorted array using Map data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output : 1 2 5 7 4 Explanation : {1, 2} appear more than one time. Approach : Take a hash map, which will store all the
4 min read
Map Policy Based Data Structure in g++
There are some data structures that are supported by g++ compiler and are not a part of the C++ standard library. One of these is: Policy-Based Data Structure, which is used for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std. This can also be used as a map, to store key and a value (pair) in a
3 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Remove duplicates from unsorted array using Set data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output: 1 2 5 7 4 Explanation: {1, 2} appear more than one time. Input: arr[] = { 3, 3, 4, 1, 1} Output: 3 4 1 Approach:
3 min read
Count-Min Sketch Data Structure with Implementation
The Count-Min Sketch is a probabilistic data structure and is defined as a simple technique to summarize large amounts of frequency data. Count-min sketch algorithm talks about keeping track of the count of things. i.e, How many times an element is present in the set. What is Count-Min Sketch?Count-min sketch approach was proposed by Graham Cormode
7 min read
Introduction to the Probabilistic Data Structure
Introduction: Probabilistic Data Structures are data structures that provide approximate answers to queries about a large dataset, rather than exact answers. These data structures are designed to handle large amounts of data in real-time, by making trade-offs between accuracy and time and space efficiency. Some common examples of Probabilistic Data
5 min read
Sort a 2D vector diagonally using Map Data Structure
Given a 2D vector mat[][] of integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in increasing order.Examples: Input: mat[][] = {{9, 4, 2}, {7, 4, 6}, {2, 3, 3}} Output: 3 4 2 3 4 6 2 7 9 Explanation: There are 5 diagonals in this matrix: 1. {2} - No need to sort 2. {7, 3} - Sort - {3, 7} 3. {9, 4, 3}
8 min read
Top 12 Data Structure Algorithms to Implement in Practical Applications in 2021
New Year...New Beginning...!!! What's your plan for this year??? (Being a programmer) Of course, if you're a programmer then this year you will also write the code, build the projects and you will solve a lot of coding questions. Let's talk about Data Structures and Algorithms... Heart of computer science and the programmer's breath to live in the
14 min read
Introduction to Universal Hashing in Data Structure
Universal hashing is a technique used in computer science and information theory for designing hash functions. It is a family of hash functions that can be efficiently computed by using a randomly selected hash function from a set of hash functions. The goal of universal hashing is to minimize the chance of collisions between distinct keys, which c
5 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Implementation on Map or Dictionary Data Structure in C
C programming language does not provide any direct implementation of Map or Dictionary Data structure. However, it doesn't mean we cannot implement one. In C, a simple way to implement a map is to use arrays and store the key-value pairs as elements of the array. How to implement Map in C? One approach is to use two arrays, one for the keys and one
3 min read
Applications, Advantages and Disadvantages of Hash Data Structure
Introduction : Imagine a giant library where every book is stored in a specific shelf, but instead of searching through endless rows of shelves, you have a magical map that tells you exactly which shelf your book is on. That's exactly what a Hash data structure does for your data! Hash data structures are a fundamental building block of computer sc
7 min read
Basic Operations for Queue in Data Structure
Basic Operations on Queue: Some of the basic operations for Queue in Data Structure are: enqueue() - Insertion of elements to the queue.dequeue() - Removal of elements from the queue.peek() or front()- Acquires the data element available at the front node of the queue without deleting it.rear() - This operation returns the element at the rear end w
11 min read
Merge Sort Tree with point update using Policy Based Data Structure
A Merge Sort Tree (MST) is a data structure that allows for efficient querying of the number of elements less than or equal to a certain value in a range of an array. It is built using a divide-and-conquer approach similar to the merge sort algorithm, where the array is recursively divided into two halves and a tree is constructed to represent the
7 min read
What is Data Structure?
A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. It refers to the logical or mathematical representation of data, as well as the implementation in a computer program. Classification:Data structures can be classified into two broad categories: Linear Data Structure: A data struct
2 min read
Stack Vs Heap Data Structure
What is Stack? A stack is a linear data structure where the last element entered exits first. The order of stack data structure might be LIFO, FILO: According to this technique, the piece that is in last will come out first. As an example, consider a stack of dishes stacked on top of each other. The plate we put last is on top, and because we take
3 min read
Heap data structure implementation in swift
A heap is a complete binary tree where each node satisfies the heap property. The heap property is different for different types of heaps but, in general, it means that each node has a value that is greater than or equal to (or less than or equal to) the values of its children nodes. Heaps are commonly used to implement priority queues, as they all
3 min read
Top 50 Problems on Queue Data Structure asked in SDE Interviews
A Queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order. We define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end. The element which is first pushed into the order, the operation
3 min read
Top 50 Problems on Matrix/Grid Data Structure asked in SDE Interviews
A Matrix/Grid is a two-dimensional array that consists of rows and columns. It is an arrangement of elements in horizontal or vertical lines of entries. Here is the collection of the Top 50 list of frequently asked interviews question on Matrix/Grid in the SDE Interviews. Problems in this Article are divided into three Levels so that readers can pr
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg