Find k-th smallest element in given n ranges in C++

C++Server Side ProgrammingProgramming

In this problem, we are given n ranges and an integer k. Our task is to find k-th smallest element in given n ranges. 

We need to find the kth smallest elements from the array which is created after combining the ranges.

Let’s take an example to understand the problem, 

Input: ranges = {{2, 5}, {7, 9}, {12, 15}}, k = 9

Output: 13

Explanation: 

The array created is {2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 15}

The smallest elements is 13

Solution Approach:

A simple solution to the problem is by creating the array from all ranges and as it is created from range it is also sorted in ascending order. Hence we just need to find the kth value of the array.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int main(){
   
   int arr[][2] = {{2, 5}, {7, 9}, {12, 15}};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 9;

   int rangeArr[1000];
   int size = 0;
   for(int i = 0; i < n; i++)
      for(int j = arr[i][0]; j <= arr[i][1]; j++) {
         rangeArr[size] = j;  
         size++;
      }
   if(k < size)
      cout<<k<<"th smallest element of the ranged array is "<<rangeArr[k]<<endl;
   else
      cout<<"invalid Index";
   return 0;
}

Output

9th smallest element of the ranged array is 13
raja
Published on 25-Jan-2021 04:50:44
Advertisements