Leetcode 1488: Avoid Flood in The City

grid47
grid47
Exploring patterns and algorithms
Jun 11, 2024 7 min read

Your country has an infinite number of lakes. Initially, all the lakes are dry, but on the nth day, the nth lake fills up with water. If it rains over a lake that is already full, there will be a flood. You need to avoid flooding by drying out lakes on some days when there is no rain.
Problem
Approach
Steps
Complexity
Input: You are given an integer array rains. The ith element in the array indicates either rain or a dry day for a lake. If the element is 0, you can choose a lake to dry. If the element is greater than 0, rain falls on the lake specified by the number.
Example: rains = [1, 2, 3, 4]
Constraints:
• 1 <= rains.length <= 10^5
• 0 <= rains[i] <= 10^9
Output: Return an array ans where each index corresponds to the ith day. If it rains, output -1, otherwise output the lake to dry.
Example: Output: [-1, -1, -1, -1]
Constraints:
• The returned array should have the same length as the input array rains.
Goal: Avoid floods by drying out lakes in a manner that ensures no lake will overflow.
Steps:
• Track lakes that are already filled.
• If rain falls over a lake, check if it was previously filled. If it was, attempt to dry one of the lakes that can be dried without causing a flood.
• If drying is impossible or no valid lake is available, return an empty array.
Goal: The input array 'rains' will have at least 1 element and at most 10^5 elements. Each element will either be 0 (no rain) or a positive integer representing the lake that will be filled by rain.
Steps:
• The array size can be large, so an efficient solution is required.
Assumptions:
• The lakes are infinite, and each lake can be filled only once.
Input: rains = [1, 2, 0, 0, 2, 1]
Explanation: On the first two days, lakes 1 and 2 fill up. On the third and fourth days, we dry lake 2 and lake 1 respectively to prevent a flood. No flooding occurs.

Input: rains = [1, 2, 0, 1, 2]
Explanation: By the third day, lakes 1 and 2 are full. No matter which lake we dry on the third day, one of them will flood.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus