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 floods in any lake.
Given an integer array rains where:
rains[i] > 0 means there will be rains over the rains[i] lake.rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.Return an array ans where:
ans.length == rains.lengthans[i] == -1 if rains[i] > 0.ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
Example 1:
Input: rains = [1,2,3,4] Output: [-1,-1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day full lakes are [1,2,3] After the fourth day full lakes are [1,2,3,4] There's no day to dry any lake and there is no flood in any lake.
Example 2:
Input: rains = [1,2,0,0,2,1] Output: [-1,-1,2,1,-1,-1] Explanation: After the first day full lakes are [1] After the second day full lakes are [1,2] After the third day, we dry lake 2. Full lakes are [1] After the fourth day, we dry lake 1. There is no full lakes. After the fifth day, full lakes are [2]. After the sixth day, full lakes are [1,2]. It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
Example 3:
Input: rains = [1,2,0,1,2] Output: [] Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day. After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
Constraints:
1 <= rains.length <= 1050 <= rains[i] <= 109Problem Overview: You are given an array rains where rains[i] represents rain over a lake on day i. If the same lake gets rain twice without being dried first, the city floods. When rains[i] == 0, you may dry exactly one lake. The task is to schedule drying operations so that no lake floods and return the drying plan.
Approach 1: Greedy with Map and Ordered Set (O(n log n) time, O(n) space)
This approach uses a greedy strategy with two data structures. Maintain a hash map that records the last day each lake was filled, and an ordered set containing indices of available dry days. When you encounter rain for lake x, check the map to see if it was previously filled. If it was, you must find a dry day after the previous rain and before the current day. Use binary search on the ordered set to locate the earliest valid dry day. Assign that day to dry lake x and remove it from the set. If no such dry day exists, flooding is unavoidable and the answer is impossible.
When rains[i] == 0, simply record the day in the set of available dry days. The greedy decision works because drying the earliest possible day preserves flexibility for future lakes. The ordered structure ensures efficient lookups and updates. This solution heavily relies on hash tables, binary search, and a greedy scheduling strategy.
Approach 2: Sliding Window with Priority Queue (O(n log n) time, O(n) space)
This variation models the problem as scheduling future conflicts. Track upcoming rains for each lake and push them into a min-heap representing the next day the lake will overflow if not dried. When a dry day appears, select the lake with the earliest upcoming rain from the heap and dry it. This ensures the most urgent lake is handled first.
During iteration, when rain fills a lake, record its next occurrence using preprocessed indices. The heap prioritizes lakes whose next rain arrives soonest, preventing imminent flooding. This technique relies on a priority queue to manage urgency. It is conceptually similar to interval scheduling problems where tasks must be completed before deadlines.
Recommended for interviews: The greedy map + ordered set solution is the most commonly expected answer. It demonstrates strong control of data structures, especially combining hash maps with binary search on sorted containers. Interviewers want to see the reasoning that the earliest valid dry day should always be chosen. The heap-based strategy also works but is less commonly implemented under interview time pressure.
This approach involves using a map to track the last filled day for each lake and a set to track available dry days. When it's a raining day, if the lake is already filled, we should look for an available dry day that comes before the current day to prevent a flood. The set helps us quickly find the nearest dry day. This approach efficiently prevents flooding, borrowing elements from greedy strategy to promptly tackle future floods.
The C solution uses a binary search tree to efficiently manage available dry days, optimizing for finding the earliest dry day possible when a lake is in jeopardy of flooding. We track known, filled lakes by their last fill-day in a map. When rain hits a lake already filled, we search our tree for the earliest available day, dry the respective lake, and update our tracking data. If no such day exists, a flood is inevitable. This provides an efficient O(N log N) solution.
Time Complexity: O(N log N) due to BST operations and map working in logarithmic time on average.
Space Complexity: O(N) for maintaining the map and tree nodes proportional to dry days.
This approach focuses on using a priority queue (or a similar data structure) to dynamically manage dry days and fulfill drying needs near the critical time when flooding becomes imminent. The key is to keep track of active periods of rain with minimum available dry day windows resolved through heap operations. This approach can be more intuitive and may align with natural sliding window functionality to resolve complex rain patterns iteratively.
Here, the C++ solution utilizes sets and maps, favoring element inclusions for representing rain and dry days. The adaptive nature resembles a sliding window technique, dynamically pivoting on active dry opportunities using set-based operations for efficient outcomes without external libraries.
Time Complexity: O(N log N) due to map and set functions.
Space Complexity: O(N) due to auxiliary space for driving statuses.
We store all sunny days in the sunny array or a sorted set, and use the hash table rainy to record the last rainy day for each lake. We initialize the answer array ans with each element set to -1.
Next, we traverse the rains array. For each rainy day i, if rainy[rains[i]] exists, it means that the lake has rained before, so we need to find the first date in the sunny array that is greater than rainy[rains[i]], and replace it with the rainy day. Otherwise, it means that the flood cannot be prevented, and we return an empty array. For each non-rainy day i, we store i in the sunny array and set ans[i] to 1.
After the traversal, we return the answer array.
The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of the rains array.
| Approach | Complexity |
|---|---|
| Use Greedy Approach with Map and Set | Time Complexity: O(N log N) due to BST operations and map working in logarithmic time on average. |
| Sliding Window with Priority Queue | Time Complexity: O(N log N) due to map and set functions. |
| Greedy + Binary Search | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Map and Ordered Set | O(n log n) | O(n) | Best general solution. Efficiently finds the earliest valid dry day using binary search. |
| Sliding Window with Priority Queue | O(n log n) | O(n) | Useful when modeling the problem as deadline scheduling with urgency handled by a heap. |
Avoid Flood in The City | Detailed Thought Process | Intuitive | Leetcode 1488 | codestorywithMIK • codestorywithMIK • 10,645 views views
Watch 9 more video solutions →Practice Avoid Flood in The City with our built-in code editor and test cases.
Practice on FleetCode