1
var avoidFlood = function (rains) {2
const n = rains.length;3
const filledLakes = new Map();4
const res = new Array(n).fill(-1);7
for (let i = 0; i < n; i++) {8
const lake = rains[i]; // lake to rain on13
} 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);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 lake18
const lake_index = filledLakes.get(lake); //19
const dry_index = binarySearch(lake_index);21
if (dry_index === dryDays.length) return []; // there was no dry day after the lake was previouly filled23
res[dryDays[dry_index]] = lake; // mark the earliest dry day that was used in our result array24
filledLakes.set(lake, i); // we need to update the day that the lake is rained on again25
dryDays.splice(dry_index, 1); // remove the dry day that was used (this is not very efficient, but it just makes our code cleaner)29
dryDays.forEach((day) => (res[day] = 1));33
function binarySearch(target) {35
let right = dryDays.length - 1;37
while (left <= right) {38
const mid = left + Math.floor((right - left) / 2);40
if (dryDays[mid] < target) left = mid + 1;