Similar Problems

Similar Problems not available

Avoid Flood In The City - Leetcode Solution

LeetCode:  Avoid Flood In The City Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table binary-search heap-priority-queue array  

The "Avoid Flood in The City" problem on LeetCode requires finding a solution to prevent floods in a city where there are multiple rainfalls. The problem can be solved using a hash table and a set.

The steps to solve the problem are:

Step 1: Create an empty hash table to store all the lakes and their corresponding index.

Step 2: Traverse the given array and check if there is a rainfall in the current day.

Step 3: If there is a rainfall, check if the corresponding lake is empty or not.

Step 4: If the lake is empty, add the lake to the hash table with its index as the value.

Step 5: If the lake is not empty, check if there is any previously visited day where the same lake was empty.

Step 6: If there exists a previously visited day where the same lake was empty, find the minimum index of such an empty day.

Step 7: If there is no previously visited day where the same lake was empty, then it is not possible to avoid the flood, so return an empty array.

Step 8: If there is a previously visited day where the same lake was empty, then fill the lake on the current day with water and remove the empty day from the hash table.

Step 9: Continue traversing the array until the end.

Step 10: After traversing the array, if there are still empty days remaining in the hash table, then fill them with water on the last day.

Step 11: Return the final result.

Here is the Python code for the solution:

def avoidFlood(rains):

    lakes = {}
    result = [-1] * len(rains)

    for i, lake in enumerate(rains):
        
        if lake == 0:
            result[i] = 1
            
        else:
            if lake in lakes:

                if not lakes[lake]:
                    return []

                else:
                    empty_day = min([x for x in lakes[lake] if x > i])
                    lakes[lake].remove(empty_day)
                    result[empty_day] = lake

            lakes[lake] = lakes.get(lake, []) + [i]

    for lake in lakes:
        for day in lakes[lake]:
            result[day] = lake

    return result

The time complexity of this solution is O(nlogn) due to the use of the min function. The space complexity is O(n) due to the use of the hash table and the set.

Avoid Flood In The City Solution Code

1