#1488
Avoid Flood in The City
MediumArrayHash TableBinary SearchGreedyHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach uses a priority queue to efficiently manage which lakes to dry. By tracking the last day it rained on each lake, we can decide which lake to dry on a day without rain to prevent floods.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a set to track full lakes and a priority queue to manage the days when we can dry lakes.
- 2Step 2: Iterate through the rains array, updating the set of full lakes when it rains.
- 3Step 3: On a dry day, choose the lake with the earliest rain day from the priority queue to dry.
- 4Step 4: If a lake is already full when it rains, return an empty array to indicate a flood is unavoidable.
solution.py17 lines
1import heapq
2
3def avoidFlood(rains):
4 full_lakes = set()
5 dry_days = []
6 ans = [-1] * len(rains)
7 for i in range(len(rains)):
8 if rains[i] > 0:
9 if rains[i] in full_lakes:
10 return []
11 full_lakes.add(rains[i])
12 else:
13 dry_days.append(i)
14 if full_lakes:
15 lake_to_dry = full_lakes.pop()
16 ans[i] = lake_to_dry
17 return ansℹ
Complexity note: The optimal solution runs in O(n log n) due to the priority queue operations, while we also use O(n) space to store the lakes and results.
- 1Using a set to track full lakes helps quickly determine if a flood will occur.
- 2Using a priority queue allows us to efficiently manage which lakes to dry on dry days.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.