Search an element in given N ranges

Given an array of N sorted ranges and a number K. The task is to find the index of the range in which K lies. If K does not lie in any of the given ranges then print -1.
Note: None of the given ranges coincide.

Examples:

Input: arr[] = { { 1, 3 }, { 4, 7 }, { 8, 11 } }, K = 6
Output: 1
6 lies in the range {4, 7} with index = 1

Input: arr[] = { { 1, 3 }, { 4, 7 }, { 9, 11 } }, K = 8
Output: -1

Naive approach: The following steps can be followed to solve the above problem.

  • Traverse all the ranges.
  • Check if the condition K >= arr[i].first && K <= arr[i].second holds in any of the iterations.
  • If the number K does not lie in any of the given range then print -1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the index of the range
// in which K lies and uses linear search
int findNumber(pair<int, int> a[], int n, int K)
{
  
    // Iterate and find the element
    for (int i = 0; i < n; i++) {
  
        // If K lies in the current range
        if (K >= a[i].first && K <= a[i].second)
            return i;
    }
  
    // K doesn't lie in any of the given ranges
    return -1;
}
  
// Driver code
int main()
{
    pair<int, int> a[] = { { 1, 3 }, { 4, 7 }, { 8, 11 } };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 6;
    int index = findNumber(a, n, k);
    if (index != -1)
        cout << index;
    else
        cout << -1;
  
    return 0;
}

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
  
# Function to return the index of the range
# in which K lies and uses linear search
def findNumber(a, n, K):
      
    # Iterate and find the element
    for i in range(0, n, 1):
          
        # If K lies in the current range
        if (K >= a[i][0] and K <= a[i][1]):
            return i
  
    # K doesn't lie in any of the
    # given ranges
    return -1
  
# Driver code
if __name__ == '__main__':
    a = [[1, 3], [4, 7], [8, 11]]
    n = len(a)
    k = 6
    index = findNumber(a, n, k)
    if (index != -1):
        print(index, end = "")
    else:
        print(-1, end = "")
          
# This code is contributed by 
# Surendra_Gangwar

chevron_right