Skip to content

Commit 4091bb6

Browse files
committedMar 21, 2025
Add solution #632
1 parent 9492b7f commit 4091bb6

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@
477477
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
478478
629|[K Inverse Pairs Array](./0629-k-inverse-pairs-array.js)|Hard|
479479
630|[Course Schedule III](./0630-course-schedule-iii.js)|Hard|
480+
632|[Smallest Range Covering Elements from K Lists](./0632-smallest-range-covering-elements-from-k-lists.js)|Hard|
480481
633|[Sum of Square Numbers](./0633-sum-of-square-numbers.js)|Medium|
481482
636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium|
482483
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 632. Smallest Range Covering Elements from K Lists
3+
* https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/
4+
* Difficulty: Hard
5+
*
6+
* You have k lists of sorted integers in non-decreasing order. Find the smallest range that
7+
* includes at least one number from each of the k lists.
8+
*
9+
* We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c
10+
* if b - a == d - c.
11+
*/
12+
13+
/**
14+
* @param {number[][]} nums
15+
* @return {number[]}
16+
*/
17+
var smallestRange = function(nums) {
18+
const k = nums.length;
19+
const listCountMap = new Map();
20+
let coveredLists = 0;
21+
let minDiff = Infinity;
22+
let minStart;
23+
let minEnd;
24+
25+
const allElements = nums.flatMap((list, listIndex) =>
26+
list.map(num => ({ num, index: listIndex }))
27+
).sort((a, b) => a.num - b.num);
28+
29+
let windowStart = 0;
30+
for (let windowEnd = 0; windowEnd < allElements.length; windowEnd++) {
31+
const currentElement = allElements[windowEnd];
32+
const listIndex = currentElement.index;
33+
const count = listCountMap.get(listIndex) ?? 0;
34+
35+
if (count === 0) coveredLists += 1;
36+
listCountMap.set(listIndex, count + 1);
37+
38+
while (coveredLists === k) {
39+
const leftElement = allElements[windowStart];
40+
const range = currentElement.num - leftElement.num;
41+
42+
if (range < minDiff) {
43+
minDiff = range;
44+
minStart = leftElement.num;
45+
minEnd = currentElement.num;
46+
}
47+
const leftListIndex = leftElement.index;
48+
const leftCount = listCountMap.get(leftListIndex);
49+
listCountMap.set(leftListIndex, leftCount - 1);
50+
if (leftCount - 1 === 0) coveredLists -= 1;
51+
windowStart += 1;
52+
}
53+
}
54+
55+
return [minStart, minEnd];
56+
};

0 commit comments

Comments
 (0)
Please sign in to comment.