#1488
Medium Algorithms Avoid flood in the city
Array Hash Table Binary Search Greedy Heap (Priority Queue)
39.0% acceptance
Feb 25, 2026
2146
615
Your country has 10^9 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 must choose one lake this day and dry it.
Return an array ans where:
ans[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.
Solution
Rust
Time O(n log n)
Space O(n)
use std::collections::{BTreeSet, HashMap};
impl Solution {
pub fn avoid_flood(rains: Vec<i32>) -> Vec<i32> {
let n = rains.len();
let mut ans = vec![1i32; n];
let mut full: HashMap<i32, usize> = HashMap::new(); // lake -> day it was filled
let mut dry_days: BTreeSet<usize> = BTreeSet::new();
for (i, &lake) in rains.iter().enumerate() {
if lake == 0 {
dry_days.insert(i);
} else {
ans[i] = -1;
if let Some(&fill_day) = full.get(&lake) {
// Need a dry day after fill_day and before i
if let Some(&d) = dry_days.range(fill_day + 1..).next() {
if d < i {
ans[d] = lake;
dry_days.remove(&d);
} else {
return vec![];
}
} else {
return vec![];
}
}
full.insert(lake, i);
}
}
ans
}
}