Avoid Flood in The City — LeetCode 1488 Python Solution
MediumGreedyArrayHash TableBinary SearchHeap (Priority Queue)
- Problem
- #1488
- Pattern
- Heap / Priority Queue
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Your country has 109 lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water.
Example
- Input
- rains = [1,2,3,4]
- Output
- [-1,-1,-1,-1]
- Explanation
- After the first day full lakes are [1]
Python solution
Python
class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
n = len(rains)
ans = [-1] * n
sunny = SortedList()
rainy = {}
for i, v in enumerate(rains):
if v:
if v in rainy:
idx = sunny.bisect_right(rainy[v])
if idx == len(sunny):
return []
ans[sunny[idx]] = v
sunny.discard(sunny[idx])
rainy[v] = i
else:
sunny.add(i)
ans[i] = 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1488. Avoid Flood in The City is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1488. Avoid Flood in The City?
- LeetCode 1488. Avoid Flood in The City is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1488. Avoid Flood in The City?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1488. Avoid Flood in The City?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1488. Avoid Flood in The City cover?
- LeetCode 1488. Avoid Flood in The City is tagged Greedy, Array, Hash Table, Binary Search and Heap (Priority Queue) on LeetCode.