LeetCode 1488: Avoid Flood in The City
Problem Description
Explanation
To solve this problem, we can simulate the process day by day. We will keep track of which lakes are full and which lakes need to be dried. We will use a set to store the full lakes and a map to store the days when each lake needs to be dried.
For each day, we will check if it is raining on a full lake. If it is, then we cannot prevent a flood and return an empty array. If it is not raining, we will dry a lake that needs to be dried (if any) and update the full lakes and the days on which they need to be dried.
The time complexity of this solution is O(n) where n is the number of days in the input array. The space complexity is also O(n) to store the full lakes and the days to dry them.
Solutions
import java.util.*;
class Solution {
public int[] avoidFlood(int[] rains) {
int n = rains.length;
int[] ans = new int[n];
Arrays.fill(ans, -1);
Map<Integer, Integer> lastRainyDay = new HashMap<>();
TreeSet<Integer> dryDays = new TreeSet<>();
for (int i = 0; i < n; i++) {
int lake = rains[i];
if (lake > 0) {
ans[i] = -1; // no need to dry a lake on rainy days
if (lastRainyDay.containsKey(lake)) {
int lastRainDay = lastRainyDay.get(lake);
Integer dryDay = dryDays.ceiling(lastRainDay);
if (dryDay == null) {
return new int[0]; // flood impossible
}
ans[dryDay] = lake;
dryDays.remove(dryDay);
}
lastRainyDay.put(lake, i);
} else {
dryDays.add(i);
}
}
return ans;
}
}
Loading editor...