Smallest range in K lists | Practice | GeeksforGeeks

Given K sorted lists of integers, KSortedArray[] of size N each. The task is to find the smallest range that includes at least one element from each of the K lists. If more than one such range's are found, return the first such range found.
Example 1:
Input:
N = 5, K = 3
KSortedArray[][] = {{1 3 5 7 9},
                    {0 2 4 6 8},
                    {2 3 5 7 11}}
Output: 1 2
Explanation: K = 3
A:[1 3 5 7 9]
B:[0 2 4 6 8]
C:[2 3 5 7 11]
Smallest range is formed by number 1
present in first list and 2 is present
in both 2nd and 3rd list.

Example 2:
Input:
N = 4, K = 3
KSortedArray[][] = {{1 2 3 4},
                    {5 6 7 8},
                    {9 10 11 12}}
Output: 4 9
Your Task : 
Complete the function findSmallestRange() that receives array , array size n and k as parameters and returns the output range (as a pair in cpp and array of size 2 in java and python)
Expected Time Complexity : O(n * k *log k)
Expected Auxilliary Space  : O(k)
0
milindprajapatmst191 month ago
# define pi pair<int, int>
# define pii pair<int, pair<int, int>>
# define mp make_pair
# define f first
# define s second

class Solution {
    public:
    pi result;
    set<pii> S;
    pi fetch() {
        return mp(S.begin()->f, S.rbegin()->f);
    }
    pi findSmallestRange(int arr[][N], int n, int k) {
        for (int i = 0; i < k; i++)
            S.insert({arr[i][0], {i, 0}});
        result = fetch();
        while (true) {
            pii p = *S.begin();
            S.erase(S.begin());
            p.s.s++;
            if (p.s.s < n) {
                S.insert({arr[p.s.f][p.s.s], {p.s.f, p.s.s}});
                pi p = fetch();
                if (result.s - result.f > p.s - p.f)
                    result = p;
            }
            else
                break;
        }
        return result;
    }
};
0
ashfaqhussainmd151 month ago
class node{       public:           int data;           int row;           int col;           node(int data,int row,int col)           {               this->row=row;               this->col=col;               this->data=data;           }   };   class compare{       public:           bool operator()(node* a,node* b)           {               return a->data>b->data;           }   };   pair<int,int> findSmallestRange(int KSortedArray[][N], int n, int k)   {         //code here         priority_queue<node*,vector<node*>,compare>q;         int mi=INT_MAX;         int ma=INT_MIN;                  for(int i=0;i<k;i++)         {             int element=KSortedArray[i][0];             mi=min(mi,element);             ma=max(ma,element);             q.push(new node(element,i,0));         }                  int start=mi;         int end=ma;                  while(!q.empty())         {             node* temp=q.top();             q.pop();                          mi=temp->data;                          if(ma-mi<end-start)             {                 start=mi;                 end=ma;             }                          if(temp->col+1<n)             {                 ma=max(ma,KSortedArray[temp->row][temp->col+1]);                 q.push(new node(KSortedArray[temp->row][temp->col+1],temp->row,temp->col+1));             }             else{                 break;             }         }                  pair<int,int>p;         p.first=start;         p.second=end;                  return p;   }
0
himanshukug19cs2 months ago
java solution
 
 static class pair implements Comparable<pair>{   int li;   int di;   int val;   pair(int li,int di,int val){       this.li=li;       this.di=di;       this.val=val;   }   public int compareTo(pair o){       return this.val-o.val;   }}static int[] findSmallestRange(int[][] arr,int n,int k){    //add your code here2    int[] ans= new int[2];    int max=Integer.MIN_VALUE;    ans[0]=arr[0][0];        PriorityQueue<pair> pq = new PriorityQueue<>();    for(int i=0;i<k;i++){        ans[0]=Math.min(ans[0],arr[i][0]);        max=Math.max(max,arr[i][0]);        pair p = new pair(i,0,arr[i][0]);        pq.add(p);    }    int d=max-ans[0];    ans[1]=max;    while(!pq.isEmpty()){        pair r= pq.poll();        if(d>max-r.val){               ans[0]=r.val;               ans[1]=max;               d=max-r.val;        }        r.di++;        if(r.di<n){            r.val=arr[r.li][r.di];            max=Math.max(max,r.val);            pq.add(r);        }        else           break;    }    return ans;}
+2
aloksinghbais022 months ago
C++ solution having time complexity as O(N*K*log(K)) and space complexity as O(K) is as follows :- 
 
Execution Time :- 0.9 / 1.5 sec
 
pair<int,int> findSmallestRange(int KSortedArray[][N], int n, int k){       set<pair<int,pair<int,int>>> s;              for(int i = 0; i < k; i++){           s.insert({KSortedArray[i][0],{i,0}});       }              pair<int,int> range = {0,100000};       int minDiff = INT_MAX;       while(true){           auto p1 = *s.rbegin(); // max           auto p2 = *s.begin(); // min                      int row = p2.second.first,col = p2.second.second;                      int currDiff = p1.first - p2.first;           if(currDiff < minDiff){               minDiff = currDiff;               range = {p2.first,p1.first};           }                      int old_ele = KSortedArray[row][col];                      auto it = s.find({old_ele,{row,col}});           s.erase(it);                      col++;           if(col == n) break;                      int new_ele = KSortedArray[row][col];           s.insert({new_ele,{row,col}});       }              return (range);   }
+1
shashikantg2 months ago
Easiest and nonMessy code with help of MULTISET.(Best use of multiset for this type of questions where we want some other element(min. in this case)  along with max. element, everytime when new item comes)
 
         int a=0,b=INT_MAX;
         int sokth[k]={0};
         
         multiset<pair<int,int> > mst;
         for(int i=0;i<k;i++)
         mst.insert({arr[i][0], i});
         
         for(int i=0;i<n*k;i++){
             pair<int,int> front=*mst.begin(), back=*mst.rbegin();
             if(abs(back.first-front.first)<abs(b-a)){
                 a=front.first; b=back.first;
             }
             mst.erase(mst.begin());
             sokth[front.second]++;
             if(sokth[front.second]==n) break;
             mst.insert({arr[front.second][sokth[front.second]], front.second});
         }
         return {a,b};
+1
agarg3be193 months ago
Using priority queue C++
typedef pair<int,pair<int,int>> pai;
class Solution{
    public:
    pair<int,int> findSmallestRange(int KSortedArray[][N], int n, int k)
    {
        pair<int,int> ans;
        int mini=INT_MAX,mx=0,minele=INT_MAX,maxele=INT_MIN,range=INT_MAX;
        pair<int,int> min_idx;
        priority_queue<pai,vector<pai>,greater<pai>> pq;
        for(int i=0;i<k;i++)
        {
            pq.push(make_pair(KSortedArray[i][0],make_pair(i,0)));
            mx=max(mx,KSortedArray[i][0]);
        }
        while(1)
        {
            mini=pq.top().first;
            min_idx=pq.top().second;
            pq.pop();
            if(mx-mini<range)
            {
                maxele=mx;
                minele=mini;
                range=(mx-mini);
                ans=make_pair(mini,mx);
            }
            int x=min_idx.first;
            int y=min_idx.second+1;
            if(y==n)
            break;
            if(KSortedArray[x][y]>mx)
            mx=KSortedArray[x][y];
            pq.push(make_pair(KSortedArray[x][y],make_pair(x,y)));
        }
        return ans;
    }
};
0
vankshu593 months ago
Set solution
class Box {
  public:
    int num;
    int numIdx;
    int arrIdx;
    
    Box(int _num, int _numIdx, int _arrIdx) {
        num = _num;
        numIdx = _numIdx;
        arrIdx = _arrIdx;
    }

};

struct comp {
	bool operator()(const Box &x, const Box &y) const { 
	    if(x.num == y.num) return x.arrIdx < y.arrIdx;
	    return x.num < y.num;
	}
};

class Solution {
  public:
    pair<int, int> findSmallestRange(int KSortedArray[][N], int n, int k) {
          set<Box, comp> s;
          for(int i = 0; i < k; i++) {
              Box b(KSortedArray[i][0], 0, i);
              // Element, element index, array index
              s.insert(b);
          }
          pair<int, int> range = {0, 1e5};
          while(1) {
              auto l = *s.begin(), r = *s.rbegin();
              int currD = r.num - l.num, prevD = range.second - range.first;
              if(currD < prevD) range = {l.num, r.num};
              int currIdx = l.numIdx;
              if(currIdx == n - 1) break;
              s.erase(s.begin());
              // Put the new element
              l.numIdx = currIdx + 1;
              l.num = KSortedArray[l.arrIdx][l.numIdx];
              s.insert(l);
          }
          return range;
    }
};
0
sinhaabhijeet93 months ago
I AM GETTING ERROR FOR A TEST CASE BUT WHEN I MANUALLY ENTER THE INPUT IN TEST AGAINST CUSTOM CODE  IT SHOW CORRECT OUTPUY. HAHA
 
pair<int,int> findSmallestRange(int KSortedArray[][N], int n, int k)   {       int i=0;       int j=0;         int max= -2147483648;         int low;         int high;         int min = 2147483647;         int range = 2147483647;         priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;         vector<vector<int>> temp;                  while(j<N)         {             if (pq.size()<k)             {                 if(KSortedArray[i][j] > max)                 {                     max = KSortedArray[i][j];                 }                 pq.push({KSortedArray[i][j],i,j});                 i++;             }                         else            {                temp.push_back(pq.top());                               min = temp[temp.size()-1][0];                if(range >(max-min))                {                    range = max - min;                    low = min;                    high = max;                }                                pq.pop();                                j = temp[temp.size()-1][2];                i = temp[temp.size()-1][1];                j++;            }                      }   return{low,high};   }
+2
cs21m0593 months ago
IF u want some nlogn approach(passes all testcases as well here), then just put all the elements in one vector and give each element the vector "ID" it belongs to.
 
Now, Sort it acc. to values.
 
Now, the ques converts to find min range such that all the “IDs” exist, just like A sliding window ques where we find all min range such that anagram exists  , etc.
 
 
 
 
 
CODE(c++) :-
 
  vector<pair<int,int>> arr;                  for(int i =  0 ; i < k ; i ++)         {             for(int   j  = 0 ; j < n ; j ++)             {                 arr.push_back({KSortedArray[i][j] , i});             }         }                  sort(arr.begin() , arr.end());                                   int count = k;                    unordered_map<int,int> m;                       int  i = 0 , j = 0 , size = arr.size();                  int min = INT_MAX;         pair<int,int> ans;                  while( j < size)         {             pair<int,int> temp = arr[j];             int val = temp.first;             int id = temp.second;                          m[id]++;                          if(m.size() < count) j++;                          else if(m.size() == count)             {                 while(m.size() == count)                 {                     if(arr[j].first - arr[i].first + 1 < min)                     {                         min = arr[j].first - arr[i].first +1;                         ans = {arr[i].first , arr[j].first };                     }                                                               m[arr[i].second]--;                                          if(m[arr[i].second] == 0)                     {                         m.erase(arr[i].second);                     }                                          i++;                                      }                 j++;             }                            }                  return ans;         
 
0
vatskratos235 months ago
struct element{ int val; int k; int pos;};class Solution{   public:   static bool sort_t(element a,element b)   {       return a.val>b.val;   }   pair<int,int> findSmallestRange(int KSortedArray[][N], int n, int k)   {       pair<int,int> ans,temp;       vector<element> vec_element;       int max_range=-1;       for(int i=0;i<k;i++)       {           element e;           e.val=KSortedArray[i][0];           e.k=i;           e.pos=0;           max_range=max(max_range,e.val);           vec_element.push_back(e);       }       make_heap(vec_element.begin(),vec_element.end(),sort_t);       ans.first=vec_element.front().val;       ans.second=max_range;       while(1)       {           int pos=vec_element.front().pos+1;           if(pos==n)               break;           else           {               int k=vec_element.front().k;               pop_heap(vec_element.begin(),vec_element.end(),sort_t);               vec_element.pop_back();               element e;               max_range=max(max_range,KSortedArray[k][pos]);               e.val=KSortedArray[k][pos];               e.pos=pos;               e.k=k;               vec_element.push_back(e);               push_heap(vec_element.begin(),vec_element.end(),sort_t);               temp.first=vec_element.front().val;               temp.second=max_range;               if(temp.second-temp.first<ans.second-ans.first)               {                   ans=temp;               }           }       }       return ans;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.