Python 1488.py
class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
result = []
size = len(rains)
last = {} # last time it rains over that lake
next = [ size ] * size # if rains[i] = x then next[i] is the next time
# it rains over the same lake
# look at rainy days
for i, r in enumerate(rains):
if r > 0:
# upcoming rain
if r in last:
next[last[r]] = i
# past rain
last[r] = i
dry = [] # min-heap of lakes that need to be dry by a certain day
for i, (r, n) in enumerate(zip(rains, next)):
if r == 0:
if dry:
day, lake = heappop(dry)
result.append(lake) # dry a lake
else:
result.append(1) # no full lakes left, don't do anything (a test case expects 1, though)
else:
if dry and dry[0][0] <= i:
# missed a deadline, there will be a flood
return []
# next day it rains over the same lake
if n < size:
heappush(dry, ( n, r ))
result.append(-1)
return result
Difficulty
and has an acceptance rate of about 39% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Greedy
- Hash Table
- Heap (Priority Queue)
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The avoidFlood method receives a list describing daily weather: a positive integer denotes rain over a specific lake, while 0 denotes a dry day on which a lake can be emptied. The goal is to produce a schedule that prevents any lake from being rained on while it already contains water. The method returns a list of the same length where -1 marks a rainy day, and a positive lake number marks the lake that is emptied on a dry day. An empty list signals that no feasible schedule exists.
Key Steps
1. Compute the next rain day for each lake
The algorithm first scans the input to record the most recent occurrence of each lake and to fill an auxiliary array next. For each rainy day i with lake r, if the lake has been seen before, the entry next[last[r]] is set to i, establishing a forward link from the previous rain to the upcoming one. The dictionary last is then updated with the current index.
last = {}
next = [size] * size
for i, r in enumerate(rains):
if r > 0:
if r in last:
next[last[r]] = i
last[r] = i
2. Maintain a min-heap of lakes that must be dried
A priority queue dry stores pairs (deadline, lake). The deadline is the next day the lake will receive rain; the heap property guarantees that the lake with the earliest deadline is at the top. This structure enables the algorithm to decide which lake to empty on each dry day.
3. Process each day and build the result
The main loop iterates over the days, unpacking the current rain value r and its pre-computed next rain day n.
-
On a dry day (
r == 0), the algorithm attempts to pop the lake with the nearest deadline from the heap. If the heap is empty, it appends a dummy value1(the problem’s test harness expects a positive integer). -
On a rainy day, the algorithm first checks whether any lake in the heap has a deadline that is already past (
dry[0][0] <= i). If such a situation occurs, a flood would be unavoidable, and the method returns an empty list. -
If the current lake will be rained on again (
n < size), the pair(n, r)is pushed onto the heap, establishing a new deadline for that lake. The result for a rainy day is always-1.
dry = []
for i, (r, n) in enumerate(zip(rains, next)):
if r == 0:
if dry:
day, lake = heappop(dry)
result.append(lake)
else:
result.append(1)
else:
if dry and dry[0][0] <= i:
return []
if n < size:
heappush(dry, (n, r))
result.append(-1)
4. Return the constructed schedule
After processing all days, the populated result list is returned.
return result
Edge Cases Handled
The implementation explicitly deals with consecutive dry days when no lakes require drying; it inserts the placeholder 1 to satisfy the expected output format. It also safeguards against a lake being rained on before it can be emptied by checking the heap’s top deadline against the current index. When a lake will never be rained on again, its deadline remains set to size, which is larger than any valid day index, effectively removing it from future consideration. The pre-allocation of next with size ensures that lakes without a subsequent rain are correctly identified without additional conditionals.
Performance Optimizations
The use of a dictionary for last provides constant-time look-ups of the most recent rain day for each lake, avoiding repeated scans. Pre-allocating the next array with a sentinel value (size) eliminates the need for dynamic resizing during the first pass. The priority queue (dry) enables the algorithm to always select the lake with the earliest upcoming rain in logarithmic time, ensuring that each lake is processed only when necessary. By separating the preprocessing of future rain days from the main scheduling loop, the method reduces redundant calculations and keeps the overall work proportional to the number of days.
ELI5 - Simplified Explanation
Imagine that there are many little lakes outside and sometimes it rains on them. When it rains on a lake, it gets full of water. If it rains on a lake that is already full, we have a big flood, which is messy. Thankfully, there are some sunny days where we have the chance to dry out one lake before the next rain starts.
The code is like a planner that keeps track of the rainy days and the sunny days. First, it looks ahead to see when each lake will get rained on again. It remembers which lake had rain most recently so it can plan which one needs to be emptied first to avoid a flood.
When the planner finds a rainy day, it makes sure to check if that lake is already full. If it is, the planner knows a flood is coming and stops. If it finds a sunny day, it looks at the list of full lakes and picks the one that is going to be rained on the soonest. It empties that lake just in time. If all the lakes are empty, it just picks any lake to dry up for fun. The code follows this plan to make sure every lake stays safe and dry throughout the week.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1319: Number of Operations to Make Network Connected
- problem 1465: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
- problem 1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
- problem 1482: Minimum Number of Days to Make m Bouquets
- problem 1524: Number of Sub-arrays With Odd Sum
- problem 1546: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
- problem 1562: Find Latest Group of Size M
- problem 1567: Maximum Length of Subarray With Positive Product
- problem 1320: Minimum Distance to Type a Word Using Two Fingers
- problem 1697: Checking Existence of Edge Length Limited Paths
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality