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

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
Avoid Flood Problem: Input → Strategy → OutputInput: [1,2,0,0,2,1]120021StrategyLake Status Tracking1Lake 1 Full2Lake 2 FullDay 0Day 1Output: [-1,-1,2,1,-1,-1]-1-121-1-1Dry lake 2Dry lake 1
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
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.5K Views
Medium Frequency
~35 min Avg. Time
567 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen