632. Smallest Range Covering Elements from K Lists #699
-
Topics: You have We define the range Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a min-heap (or priority queue) to track the smallest element from each list while maintaining a sliding window to find the smallest range that includes at least one element from each list. Approach
Let's implement this solution in PHP: 632. Smallest Range Covering Elements from K Lists <?php
/**
* @param Integer[][] $nums
* @return Integer[]
*/
function smallestRange($nums) {
// Initialize a min-heap to store (value, row_index, col_index)
$minHeap = new SplMinHeap();
$maxValue = PHP_INT_MIN; // Keep track of the maximum value in the current window
// Initialize the heap with the first element of each list
foreach ($nums as $rowIndex => $list) {
$minHeap->insert([$list[0], $rowIndex, 0]);
$maxValue = max($maxValue, $list[0]);
}
// Initialize the range with the max possible values
$rangeStart = PHP_INT_MIN;
$rangeEnd = PHP_INT_MAX;
// Process the heap until we can no longer include all lists in the window
while (!$minHeap->isEmpty()) {
list($minValue, $rowIndex, $colIndex) = $minHeap->extract();
// Update the smallest range
if ($maxValue - $minValue < $rangeEnd - $rangeStart) {
$rangeStart = $minValue;
$rangeEnd = $maxValue;
}
// Move to the next element in the same list (if it exists)
if ($colIndex + 1 < count($nums[$rowIndex])) {
$nextValue = $nums[$rowIndex][$colIndex + 1];
$minHeap->insert([$nextValue, $rowIndex, $colIndex + 1]);
$maxValue = max($maxValue, $nextValue);
} else {
// If any list is exhausted, break the loop
break;
}
}
return [$rangeStart, $rangeEnd];
}
// Example usage:
$nums = [[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]];
$result = smallestRange($nums);
print_r($result); // Output: [20, 24]
?> Explanation:
Complexity Analysis
This solution efficiently finds the smallest range that includes at least one number from each of the |
Beta Was this translation helpful? Give feedback.
We can use a min-heap (or priority queue) to track the smallest element from each list while maintaining a sliding window to find the smallest range that includes at least one element from each list.
Approach
k
lists. Each heap entry will be a tuple containing the value, the index of the list it comes from, and the index of the element in that list.