Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created October 7, 2025 17:52
Show Gist options
  • Select an option

  • Save tatsuyax25/3096587449680376bd1259d873e21fa0 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/3096587449680376bd1259d873e21fa0 to your computer and use it in GitHub Desktop.
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid flo
/**
* @param {number[]} rains
* @return {number[]}
*/
var avoidFlood = function(rains) {
const n = rains.length;
const ans = new Array(n).fill(1); // default dry days to lake 1 (will be overwritten)
const fullLakes = new Map(); // maps lake number to the day it was last filled
const dryDays = []; // stores indices of dry days
for (let i = 0; i < n; i++) {
const lake = rains[i];
if (lake > 0) {
// It's raining on lake `lake`
ans[i] = -1;
if (fullLakes.has(lake)) {
// Lake is already full - we need to dry it before today
let dried = false;
for (let j = 0; j < dryDays.length; j++) {
if (dryDays[j] > fullLakes.get(lake)) {
// We can dry this lake on dryDays[j]
ans[dryDays[j]] = lake;
dryDays.splice(j, 1); // remove used dry day
dried = true;
break;
}
}
if (!dried) return []; // flood is unavoidable
}
fullLakes.set(lake, i); // mark lake as full
} else {
// It's a dry day - store the index for later use
dryDays.push(i);
}
}
return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment