Problem: You are given n arrays of sorted integers. Write a program to find the smallest range that includes at least one integer from each n arrays.
For example:
For example:
Input: arr1[] = {4, 10, 15, 24, 26} arr2[] = {0, 9, 12, 20} arr3[] = {4, 18, 22, 30} Output: The minimum range is 5. The smallest range is [20, 24] as it contains 24 from arr1, 20 from arr2, and 22 from arr3.Approach: There are n arrays of sorted integers. Make a min heap of size n containing 1 element from each array. Keep track of min and max element and calculate the range. In min heap, minimum element is at top. Delete the minimum element and push another element instead of that from the same list to which minimum element belong. Repeat the process till any one of the n array gets empty. Keep track of minimum range. Following is the approach explained.
Array 1: [4, 10, 15, 24, 26]Array Array 2: [0, 9, 12, 20] Array 3: [5, 18, 22, 30] Min heap of size 3. containing 1 element of each list Min_Heap = [0, 4, 5] Min = 0 and Max = 5 Range - 6 We remove 0 and add 9 (belong the same array as min element i.e 0) Min_Heap = [4, 9, 5] Min = 4 and Max = 9 Range - 6 Remove 4 and add 10 Min_Heap = [5, 9, 10] Min = 5 and Max = 10 Range - 6 and so on... Keep track of min range.Following is the code:
#include <bits/stdc++.h> using namespace std; #define mp make_pair /* function to return the minimum range */ int minRange(int arr1[], int arr2[], int arr3[], int n1, int n2, int n3) { /* declaring min heap using priority queue. We are using pair<int, int> to store both the number and the array index of which the number bwlongs */ priority_queue< pair<int, int>, vector< pair<int, int> >, greater< pair<int, int> > > pq; int min_range = INT_MAX, cur_max, cur_min, cur_range, rmv_ind; int i=0, j=0, k=0; /* pushing the first element of each array */ pq.push(mp(arr1[i], 1)); pq.push(mp(arr2[j], 2)); pq.push(mp(arr3[k], 3)); /* run while loop till any one of the n array gets empty */ while( i < n1 && j < n2 && k < n3) { /* keep track of max element int the max heap */ cur_max = max(arr1[i], max(arr2[j], arr3[k])); /* min element is always on top in min heap */ cur_min = pq.top().first; /* calculating the cur_range */ cur_range = cur_max - cur_min + 1; /* updating min range */ min_range = min(min_range, cur_range); /* getting the index of array to which the min element belongs */ rmv_ind = pq.top().second; /* removing the min element */ pq.pop(); /* pushing the respective elements */ if(rmv_ind == 1) pq.push(mp(arr1[++i], 1)); else if(rmv_ind == 2) pq.push(mp(arr2[++j], 2)); else pq.push(mp(arr3[++k], 3)); } return min_range; } /* driver function */ int main() { int arr1[] = {4, 10, 15, 24, 26}; int arr2[] = {0, 9, 12, 20}; int arr3[] = {4, 18, 22, 30}; int n1 = sizeof(arr1)/sizeof(arr1[0]); int n2 = sizeof(arr2)/sizeof(arr2[0]); int n3 = sizeof(arr3)/sizeof(arr3[0]); cout<<minRange(arr1, arr2, arr3, n1, n2, n3)<<"\n"; return 0; }Output:
Minimum range is: 5