Count the number of intervals in which a given value lies in C++

Given a 2D array arr[][] containing intervals and a number ‘value’. The goal is to find the number of intervals present in arr between which value lies. For example intervals are [ [1,5], [3,7] ] and value=4 then it lies in both these intervals and count would be 2.

For Example

Input

arr[4][2] = { { 1, 20 }, { 12, 25 }, { 32, 40 }, { 15, 18 } } value=16

Output

Count of number of intervals in which a given value lies are: 3

Explanation

The value 16 lies between 1−20, 12−25 and 15−18

Input

arr[4][2] = {{ 1, 20 }, { 20,30 }, { 30, 40 }, { 40, 50 }} value=60

Output

Count of number of intervals in which a given value lies are: 0

Explanation

The value 60 is larger than all maximum ranges of intervals present in
arr[][].

Approach used in the below program is as follows

In this approach we will generate a frequency array arr_2[] for all numbers of the ranges present in arr. So for each range's arr[i][0] and arr[i][1] the frequency will be incremented in arr_2[ arr[i][0 or 1] ]. At the end we will update frequency array with arr_2[i]=arr_2[i]+arr_2[i−1] as numbers less than i-1 will also be less than i so frequency will be added. In this way we will get arr_2[value] as all ranges to which value lies.

• Take an integer array arr[][] containing ranges.

• Take an integer value as input.

• Function intervals_values(int arr[][2], int size, int value) takes arr and value and returns a count of the number of intervals in which a given value lies.

• Take frequency array arr_2[].

• Take low and highest as INT_MAX and INT_MIN.

• Traverse arr[][] using for loop from i=0 to i<size.

• Take temp as left of range and increment its frequency in arr_2[temp]

• Take temp_2 as right of range and increment its frequency in arr_2[temp_2+1]

• If temp<low set low=temp and if temp_2>highest set highest as temp_2.

• Traverse frequency array and update it arr_2[i]=arr_2[i]+arr_2[i+1].

• At the end return arr_2[value] as result.

Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
#define max 1000
int intervals_values(int arr[][2], int size, int value){
int arr_2[max];
int low = INT_MAX;
int highest = INT_MIN;
for(int i = 0; i < size; i++){
int temp = arr[i][0];
arr_2[temp] = arr_2[temp] + 1;
int temp_2 = arr[i][1];
arr_2[temp_2 + 1] = arr_2[temp_2 + 1] − 1;
if(temp < low){
low = temp;
}
if(temp_2 > highest){
highest = temp_2;
}
}
for (int i = low; i <= highest; i++){
arr_2[i] = arr_2[i] + arr_2[i − 1];
}
return arr_2[value];
}
int main(){
int arr[4][2] = { { 3, 20 }, { 2, 13 }, { 25, 30 }, { 15, 40 } };
int size = sizeof(arr) / sizeof(arr[0]);
int value = 28;
cout<<"Count the number of intervals in which a given value lies are:
"<<intervals_values(arr, size, value);
return 0;
}

Output

If we run the above code it will generate the following output −

Count the number of intervals in which a given value lies are: 18830628