Given k sorted lists of integers of size n each, find the smallest range that includes at least element from each of the k lists. If more than one smallest ranges are found, print any one of them.
Example:
Input: K = 3 arr1[] : [4, 7, 9, 12, 15] arr2[] : [0, 8, 10, 14, 20] arr3[] : [6, 12, 16, 30, 50] Output: The smallest range is [6 8] Explanation: Smallest range is formed by number 7 from the first list, 8 from second list and 6 from the third list. Input: k = 3 arr1[] : [4, 7] arr2[] : [1, 2] arr3[] : [20, 40] Output: The smallest range is [2 20] Explanation:The range [2, 20] contains 2, 4, 7, 20 which contains element from all the three arrays.
Naive Approach: Given K sorted list, find a range where there is at least one element from every list. The idea to solve the problem is very simple, keep k pointers which will constitute the elements in the range, by taking the min and max of the k elements the range can be formed. Initially, all the pointers will point to the start of all the k arrays. Store the range max to min. If the range has to be minimised then either the minimum value has to be increased or maximum value has to be decreased. The maximum value cannot be decreased as the array is sorted but the minimum value can be increased. To continue increasing the minimum value, increase the pointer of the list containing the minimum value and update the range until one of the lists exhausts.
- Algorithm:
- Create an extra space ptr of length k to store the pointers and a variable minrange initilized to a maximum value.
- Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.
- Repeat the following steps until atleast one list exhausts:
- Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0…k] array.
- Now update the minrange if current (max-min) is less than minrange.
- increment the pointer pointing to current minimum element.
-
Implementation:
C++
// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h>usingnamespacestd;#define N 5// array for storing the current index of list iintptr[501];// This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.voidfindSmallestRange(intarr[][N],intn,intk){inti, minval, maxval, minrange, minel, maxel, flag, minind;// initializing to 0 index;for(i = 0; i <= k; i++)ptr[i] = 0;minrange = INT_MAX;while(1) {// for mainting the index of list containing the minimum elementminind = -1;minval = INT_MAX;maxval = INT_MIN;flag = 0;// iterating over all the listfor(i = 0; i < k; i++) {// if every element of list[i] is traversed then break the loopif(ptr[i] == n) {flag = 1;break;}// find minimum value among all the list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i][ptr[i]] < minval) {minind = i;// update the index of the listminval = arr[i][ptr[i]];}// find maximum value among all the list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i][ptr[i]] > maxval) {maxval = arr[i][ptr[i]];}}// if any list exhaust we will not get any better answer, so break the while loopif(flag)break;ptr[minind]++;// updating the minrangeif((maxval - minval) < minrange) {minel = minval;maxel = maxval;minrange = maxel - minel;}}printf("The smallest range is [%d, %d]\n", minel, maxel);}// Driver program to test above functionintmain(){intarr[][N] = {{ 4, 7, 9, 12, 15 },{ 0, 8, 10, 14, 20 },{ 6, 12, 16, 30, 50 }};intk =sizeof(arr) /sizeof(arr[0]);findSmallestRange(arr, N, k);return0;}// This code is contributed by Aditya Krishna Namdeochevron_rightfilter_noneJava
// Java program to finds out smallest range that includes// elements from each of the given sorted lists.classGFG {staticfinalintN =5;// array for storing the current index of list istaticintptr[] =newint[501];// This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.staticvoidfindSmallestRange(intarr[][],intn,intk){inti, minval, maxval, minrange, minel =0, maxel =0, flag, minind;// initializing to 0 index;for(i =0; i <= k; i++) {ptr[i] =0;}minrange = Integer.MAX_VALUE;while(true) {// for mainting the index of list containing the minimum elementminind = -1;minval = Integer.MAX_VALUE;maxval = Integer.MIN_VALUE;flag =0;// iterating over all the listfor(i =0; i < k; i++) {// if every element of list[i] is traversed then break the loopif(ptr[i] == n) {flag =1;break;}// find minimum value among all the list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i][ptr[i]] < minval) {minind = i;// update the index of the listminval = arr[i][ptr[i]];}// find maximum value among all the list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i][ptr[i]] > maxval) {maxval = arr[i][ptr[i]];}}// if any list exhaust we will not get any better answer, so break the while loopif(flag ==1) {break;}ptr[minind]++;// updating the minrangeif((maxval - minval) < minrange) {minel = minval;maxel = maxval;minrange = maxel - minel;}}System.out.printf("The smallest range is [%d, %d]\n", minel, maxel);}// Driver program to test above functionpublicstaticvoidmain(String[] args){intarr[][] = {{4,7,9,12,15},{0,8,10,14,20},{6,12,16,30,50}};intk = arr.length;findSmallestRange(arr, N, k);}}// this code contributed by Rajput-Jichevron_rightfilter_nonePython
# Python3 program to finds out# smallest range that includes# elements from each of the# given sorted lists.N=5# array for storing the# current index of list iptr=[0foriinrange(501)]# This function takes an k sorted# lists in the form of 2D array as# an argument. It finds out smallest# range that includes elements from# each of the k lists.deffindSmallestRange(arr, n, k):i, minval, maxval, minrange, minel, maxel, flag, minind=0,0,0,0,0,0,0,0# initializing to 0 indexforiinrange(k+1):ptr[i]=0minrange=10**9while(1):# for mainting the index of list# containing the minimum elementminind=-1minval=10**9maxval=-10**9flag=0# iterating over all the listforiinrange(k):# if every element of list[i] is# traversed then break the loopif(ptr[i]==n):flag=1break# find minimum value among all the list# elements pointing by the ptr[] arrayif(ptr[i] < nandarr[i][ptr[i]] < minval):minind=i# update the index of the listminval=arr[i][ptr[i]]# find maximum value among all the# list elements pointing by the ptr[] arrayif(ptr[i] < nandarr[i][ptr[i]] > maxval):maxval=arr[i][ptr[i]]# if any list exhaust we will# not get any better answer,# so break the while loopif(flag):breakptr[minind]+=1# updating the minrangeif((maxval-minval) < minrange):minel=minvalmaxel=maxvalminrange=maxel-minelprint("The smallest range is [", minel, maxel,"]")# Driver codearr=[[4,7,9,12,15],[0,8,10,14,20],[6,12,16,30,50]]k=len(arr)findSmallestRange(arr, N, k)# This code is contributed by mohit kumarchevron_rightfilter_noneC#
// C# program to finds out smallest// range that includes elements from// each of the given sorted lists.usingSystem;classGFG {staticintN = 5;// array for storing the current index of list istaticint[] ptr =newint[501];// This function takes an k sorted// lists in the form of 2D array as// an argument. It finds out smallest range// that includes elements from each of the k lists.staticvoidfindSmallestRange(int[, ] arr,intn,intk){inti, minval, maxval, minrange,minel = 0, maxel = 0, flag, minind;// initializing to 0 index;for(i = 0; i <= k; i++) {ptr[i] = 0;}minrange =int.MaxValue;while(true) {// for mainting the index of// list containing the minimum elementminind = -1;minval =int.MaxValue;maxval =int.MinValue;flag = 0;// iterating over all the listfor(i = 0; i < k; i++) {// if every element of list[i]// is traversed then break the loopif(ptr[i] == n) {flag = 1;break;}// find minimum value among all the// list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i, ptr[i]] < minval) {minind = i;// update the index of the listminval = arr[i, ptr[i]];}// find maximum value among all the// list elements pointing by the ptr[] arrayif(ptr[i] < n && arr[i, ptr[i]] > maxval) {maxval = arr[i, ptr[i]];}}// if any list exhaust we will// not get any better answer,// so break the while loopif(flag == 1) {break;}ptr[minind]++;// updating the minrangeif((maxval - minval) < minrange) {minel = minval;maxel = maxval;minrange = maxel - minel;}}Console.WriteLine("The smallest range is"+"[{0}, {1}]\n",minel, maxel);}// Driver codepublicstaticvoidMain(String[] args){int[, ] arr = {{ 4, 7, 9, 12, 15 },{ 0, 8, 10, 14, 20 },{ 6, 12, 16, 30, 50 }};intk = arr.GetLength(0);findSmallestRange(arr, N, k);}}// This code has been contributed by 29AjayKumarchevron_rightfilter_none - Output:
The smallest range is [6 8]
-
Complexity Analysis:
- Time complexity : O(n * k2), to find the maximum and minimum in an array of length k the time required is O(k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n*k2).
- Space complexity: O(k), an extra array is required of length k so the space complexity is O(k)
Efficient approach: The approach remains the same but the time complexity can be reduced by using min-heap or priority queue. Min heap can be used to find the maximum and minimum value in logarithmic time or log k time instead of linear time. Rest of the approach remains the same.
- Algorithm:
- create an Min heap to store k elements, one from each array and a variable minrange initilized to a maximum value and also keep a variable max to store the maximum integer.
- Initially put the first element of each element from each list and store the maximum value in max.
- Repeat the following steps until atleast one list exhausts :
- To find the minimum value or min, use the top or root of the Min heap which is the minimum element.
- Now update the minrange if current (max-min) is less than minrange.
- remove the top or root element from priority queue and insert the next element from the list which contains the min element and upadate the max with the new element inserted.
-
Implementation:
C++
// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h>usingnamespacestd;#define N 5// A min heap nodestructMinHeapNode {// The element to be storedintelement;// index of the list from which the element is takeninti;// index of the next element to be picked from listintj;};// Prototype of a utility function to swap two min heap nodesvoidswap(MinHeapNode* x, MinHeapNode* y);// A class for Min HeapclassMinHeap {// pointer to array of elements in heapMinHeapNode* harr;// size of min heapintheap_size;public:// Constructor: creates a min heap of given sizeMinHeap(MinHeapNode a[],intsize);// to heapify a subtree with root at given indexvoidMinHeapify(int);// to get index of left child of node at index iintleft(inti) {return(2 * i + 1); }// to get index of right child of node at index iintright(inti) {return(2 * i + 2); }// to get the rootMinHeapNode getMin() {returnharr[0]; }// to replace root with new node x and heapify() new rootvoidreplaceMin(MinHeapNode x){harr[0] = x;MinHeapify(0);}};// Constructor: Builds a heap from a// given array a[] of given sizeMinHeap::MinHeap(MinHeapNode a[],intsize){heap_size = size;harr = a;// store address of arrayinti = (heap_size - 1) / 2;while(i >= 0) {MinHeapify(i);i--;}}// A recursive method to heapify a subtree with root at// given index. This method assumes that the subtrees// are already heapifiedvoidMinHeap::MinHeapify(inti){intl = left(i);intr = right(i);intsmallest = i;if(l < heap_size && harr[l].element < harr[i].element)smallest = l;if(r < heap_size && harr[r].element < harr[smallest].element)smallest = r;if(smallest != i) {swap(harr[i], harr[smallest]);MinHeapify(smallest);}}// This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.voidfindSmallestRange(intarr[][N],intk){// Create a min heap with k heap nodes. Every heap node// has first element of an listintrange = INT_MAX;intmin = INT_MAX, max = INT_MIN;intstart, end;MinHeapNode* harr =newMinHeapNode[k];for(inti = 0; i < k; i++) {// Store the first elementharr[i].element = arr[i][0];// index of listharr[i].i = i;// Index of next element to be stored// from listharr[i].j = 1;// store max elementif(harr[i].element > max)max = harr[i].element;}// Create the heapMinHeap hp(harr, k);// Now one by one get the minimum element from min// heap and replace it with next element of its listwhile(1) {// Get the minimum element and store it in outputMinHeapNode root = hp.getMin();// update minmin = hp.getMin().element;// update rangeif(range > max - min + 1) {range = max - min + 1;start = min;end = max;}// Find the next element that will replace current// root of heap. The next element belongs to same// list as the current root.if(root.j < N) {root.element = arr[root.i][root.j];root.j += 1;// update max elementif(root.element > max)max = root.element;}// break if we have reached end of any listelsebreak;// Replace root with next element of listhp.replaceMin(root);}cout <<"The smallest range is "<<"["<< start <<" "<< end <<"]"<< endl;;}// Driver program to test above functionsintmain(){intarr[][N] = {{ 4, 7, 9, 12, 15 },{ 0, 8, 10, 14, 20 },{ 6, 12, 16, 30, 50 }};intk =sizeof(arr) /sizeof(arr[0]);findSmallestRange(arr, k);return0;}chevron_rightfilter_noneJava
// Java program to find out smallest// range that includes elements from// each of the given sorted lists.classGFG {// A min heap nodestaticclassNode {// The element to be storedintele;// index of the list from which// the element is takeninti;// index of the next element// to be picked from listintj;Node(inta,intb,intc){this.ele = a;this.i = b;this.j = c;}}// A class for Min HeapstaticclassMinHeap {Node[] harr;// array of elements in heapintsize;// size of min heap// Constructor: creates a min heap// of given sizeMinHeap(Node[] arr,intsize){this.harr = arr;this.size = size;inti = (size -1) /2;while(i >=0) {MinHeapify(i);i--;}}// to get index of left child// of node at index iintleft(inti){return2* i +1;}// to get index of right child// of node at index iintright(inti){return2* i +2;}// to heapify a subtree with// root at given indexvoidMinHeapify(inti){intl = left(i);intr = right(i);intsmall = i;if(l < size && harr[l].ele < harr[i].ele)small = l;if(r < size && harr[r].ele < harr[small].ele)small = r;if(small != i) {swap(small, i);MinHeapify(small);}}voidswap(inti,intj){Node temp = harr[i];harr[i] = harr[j];harr[j] = temp;}// to get the rootNode getMin(){returnharr[0];}// to replace root with new node x// and heapify() new rootvoidreplaceMin(Node x){harr[0] = x;MinHeapify(0);}}// This function takes an k sorted lists// in the form of 2D array as an argument.// It finds out smallest range that includes// elements from each of the k lists.staticvoidfindSmallestRange(int[][] arr,intk){intrange = Integer.MAX_VALUE;intmin = Integer.MAX_VALUE;intmax = Integer.MIN_VALUE;intstart = -1, end = -1;intn = arr[0].length;// Create a min heap with k heap nodes.// Every heap node has first element of an listNode[] arr1 =newNode[k];for(inti =0; i < k; i++) {Node node =newNode(arr[i][0], i,1);arr1[i] = node;// store max elementmax = Math.max(max, node.ele);}// Create the heapMinHeap mh =newMinHeap(arr1, k);// Now one by one get the minimum element// from min heap and replace it with// next element of its listwhile(true) {// Get the minimum element and// store it in outputNode root = mh.getMin();// update minmin = root.ele;// update rangeif(range > max - min +1) {range = max - min +1;start = min;end = max;}// Find the next element that will// replace current root of heap.// The next element belongs to same// list as the current root.if(root.j < n) {root.ele = arr[root.i][root.j];root.j++;// update max elementif(root.ele > max)max = root.ele;}// break if we have reached// end of any listelsebreak;// Replace root with next element of listmh.replaceMin(root);}System.out.print("The smallest range is ["+ start +" "+ end +"]");}// Driver Codepublicstaticvoidmain(String[] args){intarr[][] = { {4,7,9,12,15},{0,8,10,14,20},{6,12,16,30,50} };intk = arr.length;findSmallestRange(arr, k);}}// This code is contributed by nobody_careschevron_rightfilter_noneC#
// C# program to find out smallest// range that includes elements from// each of the given sorted lists.usingSystem;usingSystem.Collections.Generic;classGFG {// A min heap nodepublicclassNode {// The element to be storedpublicintele;// index of the list from which// the element is takenpublicinti;// index of the next element// to be picked from listpublicintj;publicNode(inta,intb,intc){this.ele = a;this.i = b;this.j = c;}}// A class for Min HeappublicclassMinHeap {// array of elements in heappublicNode[] harr;// size of min heappublicintsize;// Constructor: creates a min heap// of given sizepublicMinHeap(Node[] arr,intsize){this.harr = arr;this.size = size;inti = (size - 1) / 2;while(i >= 0) {MinHeapify(i);i--;}}// to get index of left child// of node at index iintleft(inti){return2 * i + 1;}// to get index of right child// of node at index iintright(inti){return2 * i + 2;}// to heapify a subtree with// root at given indexvoidMinHeapify(inti){intl = left(i);intr = right(i);intsmall = i;if(l < size && harr[l].ele < harr[i].ele)small = l;if(r < size && harr[r].ele < harr[small].ele)small = r;if(small != i) {swap(small, i);MinHeapify(small);}}voidswap(inti,intj){Node temp = harr[i];harr[i] = harr[j];harr[j] = temp;}// to get the rootpublicNode getMin(){returnharr[0];}// to replace root with new node x// and heapify() new rootpublicvoidreplaceMin(Node x){harr[0] = x;MinHeapify(0);}}// This function takes an k sorted lists// in the form of 2D array as an argument.// It finds out smallest range that includes// elements from each of the k lists.staticvoidfindSmallestRange(int[, ] arr,intk){intrange =int.MaxValue;intmin =int.MaxValue;intmax =int.MinValue;intstart = -1, end = -1;intn = arr.GetLength(0);// Create a min heap with k heap nodes.// Every heap node has first element of an listNode[] arr1 =newNode[k];for(inti = 0; i < k; i++) {Node node =newNode(arr[i, 0], i, 1);arr1[i] = node;// store max elementmax = Math.Max(max, node.ele);}// Create the heapMinHeap mh =newMinHeap(arr1, k);// Now one by one get the minimum element// from min heap and replace it with// next element of its listwhile(true) {// Get the minimum element and// store it in outputNode root = mh.getMin();// update minmin = root.ele;// update rangeif(range > max - min + 1) {range = max - min + 1;start = min;end = max;}// Find the next element that will// replace current root of heap.// The next element belongs to same// list as the current root.if(root.j < n) {root.ele = arr[root.i, root.j];root.j++;// update max elementif(root.ele > max)max = root.ele;}elsebreak;// break if we have reached// end of any list// Replace root with next element of listmh.replaceMin(root);}Console.Write("The smallest range is ["+ start +" "+ end +"]");}// Driver CodepublicstaticvoidMain(String[] args){int[, ] arr = { { 4, 7, 9, 12, 15 },{ 0, 8, 10, 14, 20 },{ 6, 12, 16, 30, 50 } };intk = arr.GetLength(0);findSmallestRange(arr, k);}}// This code is contributed by Rajput-Jichevron_rightfilter_none - Output:
The smallest range is [6 8]
-
Complexity Analysis:
- Time complexity : O(n * k *log k).
To find the maximum and minimum in an Min Heap of length k the time required is O(log k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n * k *log k). - Space complexity: O(k).
The priority queue will store k elements so the space complexity os O(k)
- Time complexity : O(n * k *log k).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

