Talentd
FleetCode
Make and follow sheets.Sign in

Avoid Flood in The City solution and explanation

MediumArrayBinary SearchGreedyHash Table8 min read39.0% acceptanceUpdated 9 Apr 2026
Avoid Flood in The City | Detailed Thought Process | Intuitive | Leetcode 1488 | codestorywithMIKcodestorywithMIK · 33:06 · 11K viewsWatch on YouTube
9 more videos on this problem
  1. Avoid Flood in The City | Detailed Thought Process | Intuitive | Leetcode 1488 | codestorywithMIKcodestorywithMIK · 33:06 · 11K views
  2. LeetCode 1488. Avoid Flood in The City Explanation and Solutionhappygirlzt · 10:48 · 3K views
  3. Avoid Flood in The City | LeetCode 1488 | Complete Intuition ExplainedSanyam IIT Guwahati · 18:19 · 3K views
  4. 花花酱 LeetCode 1488. Avoid Flood in The City - 刷题找工作 EP337Hua Hua · 18:49 · 2K views
  5. 1488. Avoid Flood in The City | Leetcode Daily - PythonLeetcode Daily · 8:04 · 1K views
  6. FAANG INTERVIEW PREP - LEETCODE #1488 - Avoid Flood in the CityLeet Terps · 8:10 · 1K views
  7. 1488 Avoid Flood in the City Leetcode R Sai Siddhu · 11:52 · 876 views
  8. Avoid Flood in The City | LeetCode 1488 - Pythonimpoldev · 11:37 · 694 views
  9. 1488. Avoid Flood in The City (python) (Leetcode Medium)Programming Live with Larry · 32:38 · 691 views
  10. LeetCode 1488. Avoid Flood in The City Chinese Version 中文解释happygirlzt · 12:04 · 545 views

The problem

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.length
  • 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.

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 <= 105
  • 0 <= rains[i] <= 109

Approach overview

Problem 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.

Approach 1: Use Greedy Approach with Map and Set

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.

def avoidFlood(rains):
    from sortedcontainers import SortedList
    filled_lakes = {}
    dry_days = SortedList()
    result = [-1] * len(rains)
    for i, lake in enumerate(rains):
        if lake > 0:  # It's raining on the lake
            if lake in filled_lakes:
                last_fill_day = filled_lakes[lake]
                # Searching for the next available dry day after the last fill day
                idx = dry_days.bisect_right(last_fill_day)
                if idx == len(dry_days):
                    return []  # No dry day available, hence flood is inevitable
                dry_day_index = dry_days[idx]
                result[dry_day_index] = lake
                dry_days.remove(dry_day_index)  # This dry day is used
            filled_lakes[lake] = i
        else:  # It's a dry day
            dry_days.add(i)
            result[i] = 1  # placeholder value, can be any valid lake ID to dry
    return result

# Example run
print(avoidFlood([1, 2, 0, 0, 2, 1]))
import java.util.*;

public class AvoidFlood {
    public int[] avoidFlood(int[] rains) {
        Map<Integer, Integer> lakeMap = new HashMap<>();
        TreeSet<Integer> dryDays = new TreeSet<>();
        int[] result = new int[rains.length];

        for (int i = 0; i < rains.length; i++) {
            if (rains[i] > 0) {
                if (lakeMap.containsKey(rains[i])) {
                    Integer dryDay = dryDays.higher(lakeMap.get(rains[i]));
                    if (dryDay == null) {
                        return new int[0]; // Flood unavoidable
                    }
                    result[dryDay] = rains[i];
                    dryDays.remove(dryDay);
                }
                lakeMap.put(rains[i], i);
                result[i] = -1;
            } else {
                dryDays.add(i);
                result[i] = 1; // Arbitrary, will be replaced when resolving
            }
        }

        return result;
    }

    public static void main(String[] args) {
        AvoidFlood af = new AvoidFlood();
        int[] rains = {1, 2, 0, 0, 2, 1};
        int[] result = af.avoidFlood(rains);
        System.out.println(Arrays.toString(result));
    }
}
#include <iostream>
#include <vector>
#include <map>
#include <set>

using namespace std;

vector<int> avoidFlood(vector<int>& rains) {
    map<int, int> lakeMap;
    set<int> dryDays;
    vector<int> result(rains.size(), -1);

    for (int i = 0; i < rains.size(); ++i) {
        if (rains[i] > 0) {  // It's raining
            if (lakeMap.find(rains[i]) != lakeMap.end()) {
                auto it = dryDays.upper_bound(lakeMap[rains[i]]);
                if (it == dryDays.end()) return {};  // No suitable dry day available, flood
                result[*it] = rains[i];
                dryDays.erase(it);
            }
            lakeMap[rains[i]] = i;
        } else {  // Dry day
            dryDays.insert(i);
            result[i] = 1;
        }
    }
    return result;
}

int main() {
    vector<int> rains = {1, 2, 0, 0, 2, 1};
    vector<int> result = avoidFlood(rains);

    if (result.empty()) {
        cout << "[ ]" << endl;
    } else {
        for (int val : result) {
            cout << val << " ";
        }
        cout << endl;
    }

    return 0;
}
function avoidFlood(rains) {
    const lakeMap = new Map();
    const dryDays = new Set();
    const result = new Array(rains.length).fill(-1);

    for (let i = 0; i < rains.length; i++) {
        if (rains[i] > 0) { // Rain
            if (lakeMap.has(rains[i])) {
                const lastFillDay = lakeMap.get(rains[i]);
                const dryDayIter = [...dryDays].find(day => day > lastFillDay);
                if (dryDayIter === undefined) return [];
                result[dryDayIter] = rains[i];
                dryDays.delete(dryDayIter);
            }
            lakeMap.set(rains[i], i);
        } else { // Dry
            dryDays.add(i);
            result[i] = 1;
        }
    }
    return result;
}

console.log(avoidFlood([1, 2, 0, 0, 2, 1]));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOD 1000000007

typedef struct Node {
    int val;
    struct Node* left;
    struct Node* right;
} Node;

Node* insert(Node* node, int val) {
    if (node == NULL) {
        Node* temp = (Node*)malloc(sizeof(Node));
        temp->val = val;
        temp->left = temp->right = NULL;
        return temp;
    }
    if (val < node->val)
        node->left = insert(node->left, val);
    else if (val > node->val)
        node->right = insert(node->right, val);
    return node;
}

Node* minValueNode(Node* node) {
    Node* current = node;
    while (current && current->left != NULL)
        current = current->left;
    return current;
}

Node* deleteNode(Node* root, int val) {
    if (root == NULL) return root;
    if (val < root->val)
        root->left = deleteNode(root->left, val);
    else if (val > root->val)
        root->right = deleteNode(root->right, val);
    else {
        if (root->left == NULL) {
            Node* temp = root->right;
            free(root);
            return temp;
        } else if (root->right == NULL) {
            Node* temp = root->left;
            free(root);
            return temp;
        }
        Node* temp = minValueNode(root->right);
        root->val = temp->val;
        root->right = deleteNode(root->right, temp->val);
    }
    return root;
}

int* avoidFlood(int* rains, int rainsSize, int* returnSize) {
    int* res = (int*)malloc(rainsSize * sizeof(int));
    for (int i = 0; i < rainsSize; ++i) res[i] = -1;
    Node* dryDays = NULL;
    int map[100000] = {0};
    memset(map, -1, sizeof(map));
    for (int i = 0; i < rainsSize; ++i) {
        if (rains[i] > 0) {
            int lake = rains[i];
            if (map[lake] != -1) {
                Node* root = dryDays;
                while (root != NULL) {
                    if (root->val > map[lake]) {
                        res[root->val] = lake;
                        dryDays = deleteNode(dryDays, root->val);
                        break;
                    } else if (root->val <= map[lake]) {
                        root = root->right;
                    } else {
                        root = root->left;
                    }
                }
                if (root == NULL) {
                    *returnSize = 0;
                    free(res);
                    return NULL;
                }
            }
            map[lake] = i;
        } else {
            res[i] = 1;  // Arbitrary placeholder, real value set during update
            dryDays = insert(dryDays, i);
        }
    }
    *returnSize = rainsSize;
    return res;
}

int main() {
    int rains[] = {1, 2, 0, 0, 2, 1};
    int returnSize;
    int* result = avoidFlood(rains, 6, &returnSize);
    if (result) {
        for (int i = 0; i < returnSize; i++) {
            printf("%d ", result[i]);
        }
        free(result);
    } else {
        printf("[]");
    }
    return 0;
}
using System;
using System.Collections.Generic;

public class AvoidFloodInCity {
    public int[] AvoidFlood(int[] rains) {
        var lakeMap = new Dictionary<int, int>();
        var dryDays = new SortedSet<int>();
        var result = new int[rains.Length];

        for (int i = 0; i < rains.Length; i++) {
            if (rains[i] > 0) {
                if (lakeMap.TryGetValue(rains[i], out var lastFillDay)) {
                    var dryDay = dryDays.GetViewBetween(lastFillDay + 1, int.MaxValue).Min;
                    if (!dryDays.Remove(dryDay)) {
                        return Array.Empty<int>(); // Cannot prevent flood
                    }
                    result[dryDay] = rains[i];
                }
                lakeMap[rains[i]] = i;
                result[i] = -1;
            } else {
                dryDays.Add(i);
                result[i] = 1; // default, finalized when matching
            }
        }

        return result;
    }

    public static void Main() {
        var solution = new AvoidFloodInCity();
        int[] rains = {1, 2, 0, 0, 2, 1};
        var result = solution.AvoidFlood(rains);
        Console.WriteLine(string.Join(", ", result));
    }
}

This Python solution uses a SortedList from the sortedcontainers library to track dry days efficiently, as accessing the smallest available dry day is handled in logarithmic time. It maintains a map for filled lakes, updating each lake's index when rain occurs. On dry days indicated by zero, the code stores the index, allowing later retrieval to 'dry' a lake before it floods. If no dry options exist ahead of repeated rain, it returns an empty list to signify possible flooding.

Complexity

Time Complexity: O(N log N) because of the SortedList operations.
Space Complexity: O(N) to store the dry days and map of filled lakes.

Try this approach in the editor

Approach 2: Sliding Window with Priority Queue

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.

def avoidFlood(rains):
    import heapq
    lake_map = {}
    dry_days = []
    result = [-1] * len(rains)
    
    for i in range(len(rains)):
        if rains[i] > 0:
            if rains[i] in lake_map:
                # Use a heap to efficiently get the next available dry day
                next_dry_day = None
                while dry_days and dry_days[0] < lake_map[rains[i]]:
                    heapq.heappop(dry_days)
                if not dry_days:
                    return []
                next_dry_day = heapq.heappop(dry_days)
                result[next_dry_day] = rains[i]
            lake_map[rains[i]] = i
        else:
            heapq.heappush(dry_days, i)
            result[i] = 1
    return result

print(avoidFlood([1, 2, 0, 0, 2, 1]))
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <set>

using namespace std;

vector<int> avoidFlood(vector<int>& rains) {
    unordered_map<int, int> lakeToIndex;
    set<int> dryDays;
    vector<int> result(rains.size(), -1);
    
    for (int i = 0; i < rains.size(); ++i) {
        if (rains[i] > 0) {  // Rain
            if (lakeToIndex.count(rains[i])) {
                int lastDay = lakeToIndex[rains[i]];
                auto it = dryDays.lower_bound(lastDay);
                if (it == dryDays.end()) return {};  // No available dry day, flood inevitable
                result[*it] = rains[i];
                dryDays.erase(it);
            }
            lakeToIndex[rains[i]] = i;
        } else {  // Dry day
            dryDays.insert(i);
            result[i] = 1;
        }
    }
    return result;
}

int main() {
    vector<int> rains = {1, 2, 0, 0, 2, 1};
    vector<int> result = avoidFlood(rains);
    if (result.empty()) {
        cout << "[]" << endl;
    } else {
        for (int num : result) {
            cout << num << ' ';
        }
        cout << endl;
    }

    return 0;
}

The Python implementation employs a heap as a prioritized queue for managing dry days. Using this queue allows optimal discovery of dry days that can prevent flooding by aligning each prerequisite day to address anticipated repercussions across sequential days, dynamically leaning towards minimizing dry waiting periods.

Complexity

Time Complexity: O(N log N) with heap.
Space Complexity: O(N) as tracked data scales with input size.

Try this approach in the editor

Approach 3: Greedy + Binary Search

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.

import { AvlTree } from 'datastructures-js';

function avoidFlood(rains: number[]): number[] {
    const n = rains.length;
    const ans = Array(n).fill(-1);
    const sunny = new AvlTree<number>((a, b) => a - b);
    const rainy = new Map<number, number>();

    for (let i = 0; i < n; ++i) {
        const v = rains[i];
        if (v > 0) {
            if (rainy.has(v)) {
                const last = rainy.get(v)!;
                const node = sunny.ceil(last + 1);
                if (!node) return [];
                const t = node.getValue();
                ans[t] = v;
                sunny.remove(t);
            }
            rainy.set(v, i);
        } else {
            sunny.insert(i);
            ans[i] = 1;
        }
    }
    return ans;
}
func avoidFlood(rains []int) []int {
	n := len(rains)
	ans := make([]int, n)
	for i := range ans {
		ans[i] = -1
	}

	sunny := redblacktree.New[int, struct{}]()
	rainy := map[int]int{}

	for i, v := range rains {
		if v > 0 {
			if last, ok := rainy[v]; ok {
				node, found := sunny.Ceiling(last + 1)
				if !found {
					return []int{}
				}
				t := node.Key
				ans[t] = v
				sunny.Remove(t)
			}
			rainy[v] = i
		} else {
			sunny.Put(i, struct{}{})
			ans[i] = 1
		}
	}
	return ans
}
use std::collections::{BTreeSet, HashMap};

impl Solution {
    pub fn avoid_flood(rains: Vec<i32>) -> Vec<i32> {
        let n = rains.len();
        let mut ans = vec![-1; n];
        let mut sunny = BTreeSet::new();
        let mut rainy = HashMap::new();

        for (i, &v) in rains.iter().enumerate() {
            if v > 0 {
                if let Some(&last) = rainy.get(&v) {
                    if let Some(&t) = sunny.range((last + 1) as usize..).next() {
                        ans[t] = v;
                        sunny.remove(&t);
                    } else {
                        return vec![];
                    }
                }
                rainy.insert(v, i as i32);
            } else {
                sunny.insert(i);
                ans[i] = 1;
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Use Greedy Approach with Map and Set

Time Complexity: O(N log N) because of the SortedList operations.
Space Complexity: O(N) to store the dry days and map of filled lakes.

Sliding Window with Priority Queue

Time Complexity: O(N log N) with heap.
Space Complexity: O(N) as tracked data scales with input size.

Greedy + Binary Search–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy with Map and Ordered SetO(n log n)O(n)Best general solution. Efficiently finds the earliest valid dry day using binary search.
Sliding Window with Priority QueueO(n log n)O(n)Useful when modeling the problem as deadline scheduling with urgency handled by a heap.

Frequently asked questions

Is Avoid Flood in The City easy or hard?

Avoid Flood in The City is classified as Medium difficulty. The challenge is recognizing the greedy constraint that the earliest valid dry day must be chosen to avoid blocking future lakes. Implementing the correct data structure combination makes the problem manageable.

Avoid Flood in The City Python/Java solution

Most Python solutions use a dictionary for lake tracking and a sorted structure such as bisect with a list or a TreeSet equivalent. Java implementations commonly use HashMap and TreeSet. Both achieve O(n log n) time complexity.

How to solve Avoid Flood in The City in O(n)?

A strict O(n) solution is difficult because you must search for the next valid dry day dynamically. Most accepted implementations use an ordered set or priority queue, which introduces a logarithmic factor. The practical optimal complexity is O(n log n).

What is the best approach for Avoid Flood in The City?

The greedy approach using a hash map and an ordered set is the most reliable solution. Track the last rainy day for each lake and maintain a sorted set of available dry days. When a lake rains again, use binary search to find the earliest dry day after the previous rain. This ensures no lake fills twice without being dried.

Is Avoid Flood in The City asked at Google/Amazon/Meta?

This problem reflects common interview patterns used by large tech companies, especially those testing greedy scheduling and data structure design. Variants of this question have appeared in interviews at companies like Amazon and Google where candidates must coordinate events to avoid conflicts.

What data structure is used in Avoid Flood in The City?

Key data structures include a hash map to track the last rain day for each lake and an ordered set or tree structure to store available dry days. Some solutions also use a priority queue (min-heap) to prioritize lakes that will rain again soon.

What is the time complexity of Avoid Flood in The City?

The optimal solutions run in O(n log n) time with O(n) space. Each day is processed once, while operations like inserting dry days or performing binary search on an ordered set take O(log n). Heap operations in the priority queue approach also cost O(log n).

Comments

Now write it yourselfClose this page and solve Avoid Flood in The City in the editor, without looking.
Practise Avoid Flood in The City