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

In this problem, we are given a 2-D matrix arr[][2] that consists of n ranges (L, R), L-R. And Q queries each consisting of an integer value. Our task is to create a program to solve the Queries to check if a number lies in N ranges of L-R.

Problem Description − Here, we solve each query such that each element of the query lies in any one of the ranges.

their cannot be overlapping of ranges.

Let’s take an example to understand the problem,

## Input

arr[n][2] = { {5, 7}, {1, 3}, {9, 12} } n = 3 Q = 2, query = {10, 4}

## Output

Yes
No

## Explanation

A simple way to solve the problem is by solving each query and finding the range in which the elements lie. If it lies in any one of the range return true otherwise return false. Sorting the matrix based on the range values can help.

## Algorithm

Step 1 − Sort the matrix rowise i.e. based on range.

Step 2 − Loop for i -> 0 to Q, for all queries.

Step 2.1 − if element lie in any of the range, i.e. (arr[i][0] <= q && arr[i][1] >= q) -> return true.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
bool isPresent(int arr[][2], int n, int element){
for(int i = 0; i < n; i++){
if(arr[i][0] <= element && arr[i][1] >= element )
return true;
}
return false;
}
void solveQueries_Range(int arr[][2], int n, int Q, int query[]){
int temp[2];
for(int j = 0; j < (n - 1); j++){
for(int k = (j + 1); k < n; k++)
if(arr[j][0] > arr[k][0]){
temp[0] = arr[k][0]; temp[1] = arr[k][1];
arr[k][0] = arr[j][0]; arr[k][1] = arr[j][1];
arr[j][0] = temp[0]; arr[j][1] = temp[1];
}
}
for(int i = 0; i < Q; i++ ){
if(isPresent(arr, n, query[i]))
cout<<"For Query "<<(i + 1)<<": The number "<<query[i]<<" lies in the range\n";
else
cout<<"For Query "<<(i + 1)<<": The number "<<query[i]<<" does not lie in the range\n";
}
}
int main(){
int arr[][2] = { {5, 7}, {1, 3}, {9, 12} };
int n = 3;
int Q = 2;
int query[] = { 10, 4 };
solveQueries_Range(arr, n, Q, query);
return 0;
}

## Output

For Query 1: The number 10 lies in the range
For Query 2: The number 4 does not lie in the range

Updated on: 22-Dec-2020

125 Views