Smallest Range with Elements from k Sorted Lists
Last Updated :
15 May, 2025
Given a 2d integer array arr[][] of order k * n, where each row is sorted in ascending order. Your task is to find the smallest range that includes at least one element from each of the K lists. If more than one such ranges are found, return the first one.
Examples:
Input: arr[][] = [[ 4, 7, 9, 12, 15 ],
[ 0, 8, 10, 14, 20 ],
[ 6, 12, 16, 30, 50 ]]
Output: 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: arr[][] = [[ 2, 4 ],
[ 1, 7 ],
[ 20, 40 ]]
Output: 4 20
Explanation: The range [4, 20] contains 4, 7, 20 which contains element from all the three arrays.
[Naive Approach] - Using K Pointers - O(n k^2) Time and O(k) Space
The idea is to keep k pointers one for each list, starting at index 0. At each step, take the min and max of the current K elements to form a range. To minimize the range, we must increase the min value, since we can't decrease the max (all pointers start at 0). So, move the pointer of the list that has the current minimum, and update the range. Repeat until one list is exhausted.
Step By Step Implementation:
- Create a list of pointers, one for each input list, all starting at index 0.
- Repeat the process until one of the pointers reaches the end of its list.
- At each step, pick the current elements pointed by all pointers.
- Find the minimum and maximum among those elements.
- Calculate the range using the min and max values.
- If this range is smaller than the previous best, update the answer.
- Move forward the pointer of the list that had the minimum element.
- Stop when any list is exhausted, and return the best range found.
C++
// C++ program to find the smallest range
// that includes at least one element from
// each of the k sorted lists using k pointers
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
vector<int> findSmallestRange(vector<vector<int>>& arr) {
int k = arr.size();
int n = arr[0].size();
// Pointers for each of the k rows
vector<int> ptr(k, 0);
int minRange = INT_MAX;
int start = -1, end = -1;
while (true) {
int minVal = INT_MAX;
int maxVal = INT_MIN;
int minRow = -1;
// Traverse all k rows to get current min and max
for (int i = 0; i < k; i++) {
// If any list is exhausted, stop the loop
if (ptr[i] == n) {
return {start, end};
}
// Track min value and its row index
if (arr[i][ptr[i]] < minVal) {
minVal = arr[i][ptr[i]];
minRow = i;
}
// Track current max value
if (arr[i][ptr[i]] > maxVal) {
maxVal = arr[i][ptr[i]];
}
}
// Update the result range if a
// smaller range is found
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
start = minVal;
end = maxVal;
}
// Move the pointer of the
// row with minimum value
ptr[minRow]++;
}
return {start, end};
}
int main() {
vector<vector<int>> arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
vector<int> res = findSmallestRange(arr);
cout << res[0] << " " << res[1];
return 0;
}
Java
// Java program to find the smallest range
import java.util.*;
class GfG{
static ArrayList<Integer> findSmallestRange(int[][] arr) {
int k = arr.length;
int n = arr[0].length;
// Pointers for each of the k rows
int[] ptr = new int[k];
int minRange = Integer.MAX_VALUE;
int start = -1, end = -1;
while (true) {
int minVal = Integer.MAX_VALUE;
int maxVal = Integer.MIN_VALUE;
int minRow = -1;
// Traverse all k rows to get current min and max
for (int i = 0; i < k; i++) {
// If any list is exhausted, stop the loop
if (ptr[i] == n) {
ArrayList<Integer> result = new ArrayList<>();
result.add(start);
result.add(end);
return result;
}
// Track min value and its row index
if (arr[i][ptr[i]] < minVal) {
minVal = arr[i][ptr[i]];
minRow = i;
}
// Track current max value
if (arr[i][ptr[i]] > maxVal) {
maxVal = arr[i][ptr[i]];
}
}
// Update the result range if a smaller range is found
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
start = minVal;
end = maxVal;
}
// Move the pointer of the row with minimum value
ptr[minRow]++;
}
}
public static void main(String[] args) {
int[][] arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
ArrayList<Integer> res = findSmallestRange(arr);
System.out.println(res.get(0) + " " + res.get(1));
}
}
Python
# Python program to find the smallest range
def findSmallestRange(arr):
k = len(arr)
n = len(arr[0])
# Pointers for each of the k rows
ptr = [0] * k
min_range = float('inf')
start = -1
end = -1
while True:
min_val = float('inf')
max_val = float('-inf')
min_row = -1
# Traverse all k rows to get current min and max
for i in range(k):
# If any list is exhausted, stop the loop
if ptr[i] == n:
return [start, end]
# Track min value and its row index
if arr[i][ptr[i]] < min_val:
min_val = arr[i][ptr[i]]
min_row = i
# Track current max value
if arr[i][ptr[i]] > max_val:
max_val = arr[i][ptr[i]]
# Update the result range if a smaller range is found
if max_val - min_val < min_range:
min_range = max_val - min_val
start = min_val
end = max_val
# Move the pointer of the row with minimum value
ptr[min_row] += 1
if __name__ == "__main__":
arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
]
res = findSmallestRange(arr)
print(res[0], res[1])
C#
using System;
using System.Collections.Generic;
class GfG{
static List<int> findSmallestRange(int[,] arr) {
int k = arr.GetLength(0);
int n = arr.GetLength(1);
// Pointers for each of the k rows
int[] ptr = new int[k];
int minRange = int.MaxValue;
int start = -1, end = -1;
while (true) {
int minVal = int.MaxValue;
int maxVal = int.MinValue;
int minRow = -1;
// Traverse all k rows to get current min and max
for (int i = 0; i < k; i++) {
// If any list is exhausted, stop the loop
if (ptr[i] == n) {
return new List<int> { start, end };
}
int current = arr[i, ptr[i]];
if (current < minVal) {
minVal = current;
minRow = i;
}
if (current > maxVal) {
maxVal = current;
}
}
// Update the result range if a smaller range is found
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
start = minVal;
end = maxVal;
}
// Move the pointer of the row with minimum value
ptr[minRow]++;
}
}
public static void Main(string[] args) {
int[,] arr = {
{ 4, 7, 9, 12, 15 },
{ 0, 8, 10, 14, 20 },
{ 6, 12, 16, 30, 50 }
};
List<int> res = findSmallestRange(arr);
Console.WriteLine(res[0] + " " + res[1]);
}
}
JavaScript
// JavaScript program to find the smallest range
function findSmallestRange(arr) {
let k = arr.length;
let n = arr[0].length;
// Pointers for each of the k rows
let ptr = new Array(k).fill(0);
let minRange = Infinity;
let start = -1, end = -1;
while (true) {
let minVal = Infinity;
let maxVal = -Infinity;
let minRow = -1;
// Traverse all k rows to get current min and max
for (let i = 0; i < k; i++) {
// If any list is exhausted, stop the loop
if (ptr[i] === n) {
return [start, end];
}
// Track min value and its row index
if (arr[i][ptr[i]] < minVal) {
minVal = arr[i][ptr[i]];
minRow = i;
}
// Track current max value
if (arr[i][ptr[i]] > maxVal) {
maxVal = arr[i][ptr[i]];
}
}
// Update the result range if a smaller range is found
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
start = minVal;
end = maxVal;
}
// Move the pointer of the row with minimum value
ptr[minRow]++;
}
}
const arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
];
const res = findSmallestRange(arr);
console.log(res[0] + ' ' + res[1]);
[Better Approach] Using Two Pointer - O(n*k log (n*k)) Time and O(n*k) Space
The Idea is to find the smallest range problem by transforming it into a sliding window problem over a merged and sorted list of all elements from the input lists. Each element is stored along with its original list index to track its source. After sorting the combined list by value, two pointers (left
and right
) are used to define a window that moves through the list. As the window expands, a frequency map tracks how many unique lists are represented. When the window includes at least one number from every list, the algorithm tries to shrink it from the left to find a smaller valid range. The smallest such range found during this process is returned as the result.
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> findSmallestRange(vector<vector<int>>& arr) {
int k = arr.size();
// Stores the current index for each list
vector<int> pointers(k, 0);
// Stores the current smallest range
vector<int> smallestRange = {0, INT_MAX};
while (true) {
int currentMin = INT_MAX, currentMax = INT_MIN;
int minListIndex = -1;
// Find the minimum and maximum among current elements of all lists
for (int i = 0; i < k; i++) {
int value = arr[i][pointers[i]];
if (value < currentMin) {
currentMin = value;
minListIndex = i;
}
if (value > currentMax) {
currentMax = value;
}
}
// Update the smallest range if this one is smaller
if (currentMax - currentMin < smallestRange[1] - smallestRange[0]) {
smallestRange[0] = currentMin;
smallestRange[1] = currentMax;
}
// Move the pointer in the list that had the minimum value
pointers[minListIndex]++;
// If that list is exhausted, break the loop
if (pointers[minListIndex] == arr[minListIndex].size()) break;
}
return smallestRange;
}
// Driver code
int main() {
vector<vector<int>> arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
vector<int> result = findSmallestRange(arr);
cout << result[0] << " " << result[1];
return 0;
}
Java
import java.util.*;
class GfG {
// Function to find the smallest range
public static ArrayList<Integer> findSmallestRange(int[][] arr) {
int k = arr.length; // Number of lists
// Stores the current index for each list
int[] pointers = new int[k];
// Stores the current smallest range
ArrayList<Integer> smallestRange = new ArrayList<>
(Arrays.asList(0, Integer.MAX_VALUE));
// Continue the loop until one list is exhausted
while (true) {
int currentMin = Integer.MAX_VALUE, currentMax = Integer.MIN_VALUE;
int minListIndex = -1;
// Find the minimum and maximum among current elements of all lists
for (int i = 0; i < k; i++) {
int value = arr[i][pointers[i]];
// Update the current minimum
if (value < currentMin) {
currentMin = value;
minListIndex = i;
}
// Update the current maximum
if (value > currentMax) {
currentMax = value;
}
}
// Update the smallest range if this one is smaller
if (currentMax - currentMin < smallestRange.get(1) - smallestRange.get(0)) {
smallestRange.set(0, currentMin);
smallestRange.set(1, currentMax);
}
// Move the pointer in the list that had the minimum value
pointers[minListIndex]++;
// If that list is exhausted, break the loop
if (pointers[minListIndex] == arr[minListIndex].length) break;
}
return smallestRange; // Return the result as ArrayList
}
// Driver code
public static void main(String[] args) {
int[][] arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
ArrayList<Integer> result = findSmallestRange(arr);
System.out.println(result.get(0) + " " + result.get(1));
}
}
Python
def findSmallestRange(arr):
k = len(arr) # Number of lists
# Stores the current index for each list
pointers = [0] * k
# Stores the current smallest range
smallestRange = [0, float('inf')]
# Continue the loop until one list is exhausted
while True:
currentMin = float('inf')
currentMax = -float('inf')
minListIndex = -1
# Find the minimum and maximum among current elements of all lists
for i in range(k):
value = arr[i][pointers[i]]
# Update the current minimum
if value < currentMin:
currentMin = value
minListIndex = i
# Update the current maximum
if value > currentMax:
currentMax = value
# Update the smallest range if this one is smaller
if currentMax - currentMin < smallestRange[1] - smallestRange[0]:
smallestRange[0] = currentMin
smallestRange[1] = currentMax
# Move the pointer in the list that had the minimum value
pointers[minListIndex] += 1
# If that list is exhausted, break the loop
if pointers[minListIndex] == len(arr[minListIndex]):
break
return smallestRange # Return the result as a list
# Driver code
if __name__ == "__main__":
arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
]
result = findSmallestRange(arr)
print(result[0], result[1])
C#
using System;
using System.Collections.Generic;
class GfG{
// Function to find the smallest range
public static List<int> findSmallestRange(int[,] arr) {
int k = arr.GetLength(0); // Number of lists (rows)
// Stores the current index for each list (row)
int[] pointers = new int[k];
// Stores the current smallest range
List<int> smallestRange = new List<int> { 0, int.MaxValue };
// Continue the loop until one list is exhausted
while (true) {
int currentMin = int.MaxValue, currentMax = int.MinValue;
int minListIndex = -1;
// Find the minimum and maximum among current elements
// of all lists
for (int i = 0; i < k; i++) {
int value = arr[i, pointers[i]];
// Update the current minimum
if (value < currentMin) {
currentMin = value;
minListIndex = i;
}
// Update the current maximum
if (value > currentMax) {
currentMax = value;
}
}
// Update the smallest range if this one is smaller
if (currentMax - currentMin < smallestRange[1] - smallestRange[0]) {
smallestRange[0] = currentMin;
smallestRange[1] = currentMax;
}
// Move the pointer in the list that had the minimum value
pointers[minListIndex]++;
// If that list is exhausted, break the loop
if (pointers[minListIndex] == arr.GetLength(1)) break;
}
return smallestRange; // Return the result as List<int>
}
// Driver code
public static void Main(string[] args) {
int[,] arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
List<int> result = findSmallestRange(arr);
Console.WriteLine(result[0] + " " + result[1]);
}
}
JavaScript
function findSmallestRange(arr) {
const k = arr.length; // Number of lists
// Stores the current index for each list
let pointers = new Array(k).fill(0);
// Stores the current smallest range
let smallestRange = [0, Number.MAX_VALUE];
// Continue the loop until one list is exhausted
while (true) {
let currentMin = Number.MAX_VALUE, currentMax = -Number.MAX_VALUE;
let minListIndex = -1;
// Find the minimum and maximum among current elements of all lists
for (let i = 0; i < k; i++) {
const value = arr[i][pointers[i]];
// Update the current minimum
if (value < currentMin) {
currentMin = value;
minListIndex = i;
}
// Update the current maximum
if (value > currentMax) {
currentMax = value;
}
}
// Update the smallest range if this one is smaller
if (currentMax - currentMin < smallestRange[1] - smallestRange[0]) {
smallestRange[0] = currentMin;
smallestRange[1] = currentMax;
}
// Move the pointer in the list that had the minimum value
pointers[minListIndex]++;
// If that list is exhausted, break the loop
if (pointers[minListIndex] === arr[minListIndex].length) break;
}
return smallestRange; // Return the result as an array
}
// Driver code
const arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
];
const result = findSmallestRange(arr);
console.log(result[0], result[1]);
[Efficient Approach] - Using Min Heap - O(n k Log k) Time and O(k) Space
Min-Heap can be used to find the minimum value in logarithmic time or log k time instead of linear time. To find the max value, we initialize the max value of all 0 indexes initially. For rest of the max values in the loop, we simply compare the current max value with the next item from the list from which the min item is being removed. Rest of the approach remains the same.
Step By Step Implementation:
- Create a Min-Heap to store K elements, one from each array, and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.
- Initially put the first element from each list and store the maximum value in max.
- Repeat the following steps until at least one list exhausts :
- 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 the current (max-min) is less than minrange.
- Remove the top or root element from the priority queue, insert the next element from the list containing the min element
- Update the max with the new element inserted if the new element is greater than the previous max.
C++
#include <bits/stdc++.h>
using namespace std;
// Struct to represent elements in the heap
struct Node {
int val, row, col;
bool operator>(const Node& other) const {
return val > other.val;
}
};
// Function to find the smallest range
vector<int> findSmallestRange(vector<vector<int>>& arr) {
int N = arr.size(); // Number of rows
int K = arr[0].size(); // Number of columns (same for each row)
priority_queue<Node, vector<Node>, greater<Node>> pq;
int maxVal = INT_MIN;
// Push the first element of each list into the min-heap
for (int i = 0; i < N; i++) {
pq.push({arr[i][0], i, 0});
maxVal = max(maxVal, arr[i][0]);
}
int minRange = INT_MAX, minEl, maxEl;
while (true) {
Node curr = pq.top(); pq.pop();
int minVal = curr.val;
// Update range if better
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
minEl = minVal;
maxEl = maxVal;
}
// If we've reached the end of a list, break
if (curr.col + 1 == K) break;
// Push next element from the same list
int nextVal = arr[curr.row][curr.col + 1];
pq.push({nextVal, curr.row, curr.col + 1});
maxVal = max(maxVal, nextVal);
}
return {minEl, maxEl};
}
// Driver code
int main() {
vector<vector<int>> arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
vector<int> result = findSmallestRange(arr);
cout << result[0] << " " << result[1];
return 0;
}
Java
import java.util.*;
// Class to represent elements in the heap
class Node implements Comparable<Node> {
int val, row, col;
Node(int val, int row, int col) {
this.val = val;
this.row = row;
this.col = col;
}
// For min-heap based on value
public int compareTo(Node other) {
return this.val - other.val;
}
}
class GfG {
// Function to find the smallest range
static ArrayList<Integer> findSmallestRange(int[][] arr) {
int k = arr.length;
int n = arr[0].length;
PriorityQueue<Node> pq = new PriorityQueue<>();
int maxVal = Integer.MIN_VALUE;
// Push the first element of each list into the min-heap
for (int i = 0; i < k; i++) {
pq.add(new Node(arr[i][0], i, 0));
maxVal = Math.max(maxVal, arr[i][0]);
}
int minRange = Integer.MAX_VALUE, minEl = -1, maxEl = -1;
while (true) {
Node curr = pq.poll();
int minVal = curr.val;
// Update range if better
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
minEl = minVal;
maxEl = maxVal;
}
// If we've reached the end of a list, break
if (curr.col + 1 == n)
break;
// Push next element from the same list
int nextVal = arr[curr.row][curr.col + 1];
pq.add(new Node(nextVal, curr.row, curr.col + 1));
maxVal = Math.max(maxVal, nextVal);
}
// Return result as ArrayList
ArrayList<Integer> result = new ArrayList<>();
result.add(minEl);
result.add(maxEl);
return result;
}
// Driver code
public static void main(String[] args) {
int[][] arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
ArrayList<Integer> res = findSmallestRange(arr);
System.out.println(res.get(0) + " " + res.get(1));
}
}
Python
import heapq
# Function to find the smallest range
def findSmallestRange(arr):
k = len(arr)
n = len(arr[0])
heap = []
maxVal = float('-inf')
# Push the first element of each
# list into the min-heap
for i in range(k):
heapq.heappush(heap, (arr[i][0], i, 0))
maxVal = max(maxVal, arr[i][0])
minRange = float('inf')
minEl = maxEl = -1
while True:
minVal, row, col = heapq.heappop(heap)
# Update range if better
if maxVal - minVal < minRange:
minRange = maxVal - minVal
minEl = minVal
maxEl = maxVal
# If we've reached the end of a list, break
if col + 1 == n:
break
# Push next element from the same list
nextVal = arr[row][col + 1]
heapq.heappush(heap, (nextVal, row, col + 1))
maxVal = max(maxVal, nextVal)
return [minEl, maxEl]
# Driver code
if __name__ == "__main__":
arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
]
res = findSmallestRange(arr)
print(res[0], res[1])
C#
using System;
using System.Collections.Generic;
// Class to represent elements in the heap
class Node : IComparable<Node> {
public int val, row, col;
public Node(int val, int row, int col) {
this.val = val;
this.row = row;
this.col = col;
}
// For min-heap based on value
public int CompareTo(Node other) {
if (this.val != other.val)
return this.val.CompareTo(other.val);
// To avoid duplicate keys in SortedSet
if (this.row != other.row)
return this.row.CompareTo(other.row);
return this.col.CompareTo(other.col);
}
}
class GfG {
// Function to find the smallest range
static List<int> findSmallestRange(int[,] arr) {
int k = arr.GetLength(0);
int n = arr.GetLength(1);
var pq = new SortedSet<Node>();
int maxVal = int.MinValue;
// Push the first element of each list into the min-heap
for (int i = 0; i < k; i++) {
var node = new Node(arr[i, 0], i, 0);
pq.Add(node);
maxVal = Math.Max(maxVal, arr[i, 0]);
}
int minRange = int.MaxValue, minEl = -1, maxEl = -1;
while (true) {
var curr = GetMin(pq);
pq.Remove(curr);
int minVal = curr.val;
// Update range if better
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
minEl = minVal;
maxEl = maxVal;
}
// If we've reached the end of a list, break
if (curr.col + 1 == n)
break;
// Push next element from the same list
int nextVal = arr[curr.row, curr.col + 1];
var nextNode = new Node(nextVal, curr.row, curr.col + 1);
pq.Add(nextNode);
maxVal = Math.Max(maxVal, nextVal);
}
return new List<int> { minEl, maxEl }; // Return result as List<int>
}
// Helper to get the minimum element (first element in SortedSet)
static Node GetMin(SortedSet<Node> pq) {
foreach (var node in pq)
return node;
return null;
}
// Driver code
static void Main() {
int[,] arr = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
List<int> res = findSmallestRange(arr);
Console.WriteLine(res[0] + " " + res[1]);
}
}
JavaScript
class Node {
constructor(val, row, col) {
this.val = val;
this.row = row;
this.col = col;
}
}
// Function to find the smallest range
function findSmallestRange(arr) {
const k = arr.length;
const n = arr[0].length;
const heap = new MinHeap();
let maxVal = -Infinity;
// Push the first element of each list into the min-heap
for (let i = 0; i < k; i++) {
heap.push(new Node(arr[i][0], i, 0));
maxVal = Math.max(maxVal, arr[i][0]);
}
let minRange = Infinity;
let minEl = -1, maxEl = -1;
while (true) {
const curr = heap.pop();
const minVal = curr.val;
// Update range if better
if (maxVal - minVal < minRange) {
minRange = maxVal - minVal;
minEl = minVal;
maxEl = maxVal;
}
// If we've reached the end of a list, break
if (curr.col + 1 === n) break;
// Push next element from the same list
const nextVal = arr[curr.row][curr.col + 1];
heap.push(new Node(nextVal, curr.row, curr.col + 1));
maxVal = Math.max(maxVal, nextVal);
}
return [minEl, maxEl];
}
// Min-heap comparator
class MinHeap {
constructor() {
this.heap = [];
}
push(node) {
this.heap.push(node);
this._heapifyUp();
}
pop() {
if (this.size() === 1) return this.heap.pop();
const top = this.heap[0];
this.heap[0] = this.heap.pop();
this._heapifyDown();
return top;
}
top() {
return this.heap[0];
}
size() {
return this.heap.length;
}
_heapifyUp() {
let idx = this.size() - 1;
while (idx > 0) {
let parent = Math.floor((idx - 1) / 2);
if (this.heap[parent].val <= this.heap[idx].val) break;
[this.heap[parent], this.heap[idx]] = [this.heap[idx], this.heap[parent]];
idx = parent;
}
}
_heapifyDown() {
let idx = 0;
const n = this.size();
while (true) {
let left = 2 * idx + 1;
let right = 2 * idx + 2;
let smallest = idx;
if (left < n && this.heap[left].val < this.heap[smallest].val) {
smallest = left;
}
if (right < n && this.heap[right].val < this.heap[smallest].val) {
smallest = right;
}
if (smallest === idx) break;
[this.heap[smallest], this.heap[idx]] = [this.heap[idx], this.heap[smallest]];
idx = smallest;
}
}
}
// Driver code
const arr = [
[4, 7, 9, 12, 15],
[0, 8, 10, 14, 20],
[6, 12, 16, 30, 50]
];
const res = findSmallestRange(arr);
console.log(res[0] + " " + res[1]);
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem