diff --git a/1488. Avoid Flood in The City b/1488. Avoid Flood in The City new file mode 100644 index 0000000..caed2f7 --- /dev/null +++ b/1488. Avoid Flood in The City @@ -0,0 +1,35 @@ +class Solution { +public: + vector avoidFlood(vector& rains) { + set zer; // stores indices of days we can dry (rains[i] == 0) + int n = rains.size(); + vector ans(n, -1); // result array + unordered_map M; // lake -> last day it was filled + + for (int i = 0; i < n; i++) { + if (rains[i] == 0) { + // We can dry some lake later + zer.insert(i); + ans[i] = 1; // default, can be updated later + } else { + int lake = rains[i]; + // If lake already has water, we need to dry it before raining again + if (M.find(lake) != M.end()) { + int lastRainDay = M[lake]; + // Find first zero-day after last rain day + auto up = zer.upper_bound(lastRainDay); + if (up == zer.end()) { + // No zero-day available to dry => flood + return {}; + } + // Use that day to dry the lake + ans[*up] = lake; + zer.erase(up); + } + // Update the last rain day for this lake + M[lake] = i; + } + } + return ans; + } +};