![]() |
VOOZH | about |
Given a 2D integer array mat[][], where each row is sorted in ascending order, find the smallest range that includes at least one element from each of the rows. If more than one such range exists, consider the first one.
Note: If there are two possible ranges [a, b] and [c, d] with the same size, choose the one with the smaller starting value, i.e., consider [a, b] if a < c.
Examples:
Input: mat[][] = [[4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50]]
Output: [6, 8]
Explanation: Smallest range [6, 8] include at least one element from each rows(6, 7, 8).Input: mat[][] = [[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
Table of Content
The idea is to try all possible combinations by picking one element from each row and forming a range [min, max] from these elements. Then, track the range with the smallest size among all possible combinations.
Why Itβs Not Feasible?
For each row, if there are n elements, the total number of combinations is n Γ n Γ β¦ Γ n = n^k. This grows exponentially with k. Even for small n and moderate k, it becomes computationally infeasible.
The idea is to keep one pointer for each row, initially all pointers start at the first element of their respective rows. These k elements form one possible set containing one element from each row.
Now, check:
- The minimum among these k elements β this could be the current low.
- The maximum among these k elements β this could be the current high.
So, the current range = [min, max]. Now we have to minimize (max - min) and find the smallest possible range. To possibly shrink the range, we must move forward in the row that currently contributes the smallest element and continue this process until one of the rows runs out of elements.
6 8
This approach is an optimization over the naive method. In the naive version, we explicitly search for the minimum element among the k current elements in every iteration. To improve efficiency, we use a min-heap that helps us quickly get the minimum element. Each heap node stores the element value along with its row and column index(To know from which row the element belongs). We start by inserting the first element of each row into the heap and track the current maximum. Then, we repeatedly extract the minimum element from the heap, update the smallest range if needed, and insert the next element from the same row into the heap while updating the maximum. This continues until one of the rows is exhausted.
6 8