Avoid Flood in The City - 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. 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] > 0means there will be rains over therains[i]lake.rains[i] == 0means there are no rains this day and you must choose one lake this day and dry it.
Return an array ans where:
ans.length == rains.lengthans[i] == -1ifrains[i] > 0.ans[i]is the lake you choose to dry in the ith day ifrains[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.
Input & Output
Example 1 — Basic Case
$
Input:
rains = [1,2,3,4]
›
Output:
[-1,-1,-1,-1]
💡 Note:
After each rain, the lake becomes full. No lake gets rained on twice, so no floods occur. All rainy days return -1.
Example 2 — Need to Dry Lakes
$
Input:
rains = [1,2,0,0,2,1]
›
Output:
[-1,-1,2,1,-1,-1]
💡 Note:
Day 0: Lake 1 fills. Day 1: Lake 2 fills. Day 2: Dry lake 2. Day 3: Dry lake 1. Day 4: Lake 2 can fill again (was dried). Day 5: Lake 1 can fill again (was dried).
Example 3 — Impossible Case
$
Input:
rains = [1,2,0,1,2]
›
Output:
[]
💡 Note:
Lake 1 fills on day 0, lake 2 fills on day 1. Day 2 is dry - we can only dry one lake. Day 3 rains on lake 1 again (still full), and day 4 rains on lake 2 again (still full). We can't prevent both floods with only one dry day.
Constraints
- 1 ≤ rains.length ≤ 105
- 0 ≤ rains[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
rains[i] > 0 means rain on lake i, rains[i] = 0 means dry day
2
Track Lakes
Monitor which lakes are full to prevent double-rain floods
3
Strategic Drying
Use dry days optimally to empty lakes before they flood
Key Takeaway
🎯 Key Insight: Use the earliest available dry day after a lake fills to prevent future floods efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code