Queries to check if a number lies in N ranges of L-R in C++


In this problem, we are given N ranges [L, R] and Q queries each containing a number val. Our task is to create a program to solve Queries to check if a number lies in N ranges of L-R in C++.

Problem Description

We are given N ranges of type of [L, R] that contain integer values from L to R, for example, range [3, 6] contains 3,4,5,6. In each query, we are given a val, whose presence is to be checked. The program will return true if the val is present in any one of the ranges otherwise it will return false.

Let’s take an example to understand the problem,

Input:ranges[N] = {{2, 4}, {6,7}, {9, 12}}

Q = 3

Query = {1, 7, 10}

Output:Not Present

Present

Present

Explanation

For query 1: the number 1 is not present in any of the range.

For query 2: the number 7 is present in the range {6, 7}.

For query 1: the number 10 is present in the range {9, 12}.

Solution Approach

We need to check if the val is present in any of the range, so we need to check it val corresponding to all ranges. For this, we will use a hashmap. Storing the L and R of the range separately and then searching using binary search algorithms will make the solution easily.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
vector<int> v;
unordered_map<int, int> mpp;
void initialiseMap(int a[][2], int n){
   for (int i = 0; i < n; i++) {
      v.push_back(a[i][0]);
      mpp[a[i][0]] = 1;
      v.push_back(a[i][1]);
      mpp[a[i][1]] = 2;
   }
   sort(v.begin(), v.end());
}
bool isElementPresent(int val) {
   int ind = lower_bound(v.begin(), v.end(), val) - v.begin();
   if (v[ind] == val)
      return true;
   else {
      if (mpp[v[ind]] == 2)
         return true;
      else
         return false;
   }
}
int main(){
   int arr[][2] = {{2, 4}, {6,7}, {9, 12}};
   int n = 3;
   int Q = 3;
   int query[] = { 1, 7, 10 };
   initialiseMap(arr, n);
   for(int i = 0; i < Q; i++){
      cout<<"For Query "<<(i+1);
      if(isElementPresent(query[i]))
         cout<<": The given digit "<<query[i]<<" is present in one of the given ranges\n";
      else
         cout<<": The given digit "<<query[i]<<" is not present in any of the given ranges\n";
   }
   return 0;
}

Output

For Query 1: The given digit 1 is not present in any of the given ranges
For Query 2: The given digit 7 is present in one of the given ranges
For Query 3: The given digit 10 is present in one of the given ranges

Updated on: 09-Oct-2020

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements