Avoid Flood in The City LeetCode solution in JavaScript

1
var avoidFlood = function (rains) {
2
const n = rains.length;
3
const filledLakes = new Map();
4
const res = new Array(n).fill(-1);
5
const dryDays = [];
6

7
for (let i = 0; i < n; i++) {
8
const lake = rains[i]; // lake to rain on
9

10
if (lake === 0) {
11
// It is a dry day
12
dryDays.push(i);
13
} else if (!filledLakes.has(lake)) {
14
// The lake is not filled yet, so we let it be filled (we just don't want it to be rained on again and be flooded)
15
filledLakes.set(lake, i);
16
} else {
17
// The lake is already filled. We want to see if a dry day was available after the lake was previously rained on so that we can empty the lake
18
const lake_index = filledLakes.get(lake); //
19
const dry_index = binarySearch(lake_index);
20

21
if (dry_index === dryDays.length) return []; // there was no dry day after the lake was previouly filled
22

23
res[dryDays[dry_index]] = lake; // mark the earliest dry day that was used in our result array
24
filledLakes.set(lake, i); // we need to update the day that the lake is rained on again
25
dryDays.splice(dry_index, 1); // remove the dry day that was used (this is not very efficient, but it just makes our code cleaner)
26
}
27
}
28

29
dryDays.forEach((day) => (res[day] = 1));
30

31
return res;
32

33
function binarySearch(target) {
34
let left = 0;
35
let right = dryDays.length - 1;
36

37
while (left <= right) {
38
const mid = left + Math.floor((right - left) / 2);
39

40
if (dryDays[mid] < target) left = mid + 1;
41
else right = mid - 1;
42
}
43

44
return left;
45
}
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0