LeetCode 0632. Smallest Range Covering Elements from K Lists Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0632. Smallest Range Covering Elements from K Lists

Description

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

 

Example 1:

Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
Explanation: 
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Example 2:

Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]

 

Constraints:

  • nums.length == k
  • 1 <= k <= 3500
  • 1 <= nums[i].length <= 50
  • -105 <= nums[i][j] <= 105
  • nums[i] is sorted in non-decreasing order.

Solutions

Solution 1: Sorting + Sliding Window

We construct a data item (x, i) for each number x and its group i, and store these items in a new array t. Then, we sort t by the value of the numbers (similar to merging multiple sorted arrays into a new sorted array).

Next, we traverse each data item in t, focusing on the group to which each number belongs. We use a hash table to record the groups of numbers within the sliding window. If the number of groups is k, it means the current window meets the problem's requirements. At this point, we calculate the start and end positions of the window and update the answer.

The time complexity is O(n × log n), and the space complexity is O(n). Here, n is the total number of numbers in all arrays.

PythonJavaC++GoRust
class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: t = [(x, i) for i, v in enumerate(nums) for x in v] t.sort() cnt = Counter() ans = [-inf, inf] j = 0 for i, (b, v) in enumerate(t): cnt[v] += 1 while len(cnt) == len(nums): a = t[j][0] x = b - a - (ans[1] - ans[0]) if x < 0 or (x == 0 and a < ans[0]): ans = [a, b] w = t[j][1] cnt[w] -= 1 if cnt[w] == 0: cnt.pop(w) j += 1 return ans(code-box)

Solution 2: Priority Queue (Heap)

TypeScriptJavaScript
const smallestRange = (nums: number[][]): number[] => { const pq = new PriorityQueue<number[]>((a, b) => a[0] - b[0]); const n = nums.length; let [l, r, max] = [0, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]; for (let j = 0; j < n; j++) { const x = nums[j][0]; pq.enqueue([x, j, 0]); max = Math.max(max, x); } while (pq.size() === n) { const [min, j, i] = pq.dequeue(); if (max - min < r - l) { [l, r] = [min, max]; } const iNext = i + 1; if (iNext < nums[j].length) { const next = nums[j][iNext]; pq.enqueue([next, j, iNext]); max = Math.max(max, next); } } return [l, r]; };(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !