Member-only story
Leetcode 1488: Avoid Flood in The City
2 min readJun 24, 2020
In this Leetcode problem, we need to find a way to prevent flood given some specific rules:
Solution
A few ideas to solve that problem:
- We want to keep track of last time it rained for each city in
fullLakes
, aMap<Integer, Integer>
. - One idea is that each time it rains to a city where it rained before, we want to find a dry day in between the 2 rain days so that we can dry the lake.
- The optimal way to do it is to choose the smallest such available dry day.
- To do that we store all available dry day in a
TreeSet<Integer> noRain
. - Once we find the dry day we update the
int[] res
. - At the end we fill the remaining dry days with 1s.
class Solution {
public int[] avoidFlood(int[] rains) {
// Keep track of full lakes and the last rain date for them.
Map<Integer, Integer> fullLakes = new HashMap<>();
// Keep track of days with no rain that we didn't use yet.
TreeSet<Integer> noRain = new TreeSet<>();
int n = rains.length;
// Hold result to return
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int rain = rains[i];
if (rain == 0) {
noRain.add(i);
} else {…