LeetCode 1488: Avoid Flood in The City Solution
Master LeetCode problem 1488 (Avoid Flood in The City), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1488. Avoid Flood in The City
Problem Explanation
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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1488 (Avoid Flood in The City)?
This page provides optimized solutions for LeetCode problem 1488 (Avoid Flood in The City) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1488 (Avoid Flood in The City)?
The time complexity for LeetCode 1488 (Avoid Flood in The City) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1488 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1488 in Java, C++, or Python.