Avoid Flood in The City - Problem
Flood Prevention Simulation
You're managing a water system for a city with 109 lakes. Initially, all lakes are empty. Your task is to prevent flooding by strategically drying lakes on no-rain days.
How it works:
• When
• When
• If it rains on an already full lake, there's a flood (game over!)
Goal: Return an array where:
•
•
If flooding is unavoidable, return an empty array. Multiple valid solutions may exist.
You're managing a water system for a city with 109 lakes. Initially, all lakes are empty. Your task is to prevent flooding by strategically drying lakes on no-rain days.
How it works:
• When
rains[i] > 0: It rains on lake number rains[i], filling it completely• When
rains[i] == 0: No rain - you must choose one lake to dry• If it rains on an already full lake, there's a flood (game over!)
Goal: Return an array where:
•
ans[i] = -1 for rainy days•
ans[i] = lake_number for the lake you dry on no-rain daysIf flooding is unavoidable, return an empty array. Multiple valid solutions may exist.
Input & Output
basic_case.py — Python
$
Input:
rains = [1, 2, 3, 4]
›
Output:
[-1, -1, -1, -1]
💡 Note:
All days have rain, no dry days to worry about. Each lake gets filled once, so no floods occur.
dry_and_flood.py — Python
$
Input:
rains = [1, 2, 0, 0, 2, 1]
›
Output:
[-1, -1, 2, 1, -1, -1]
💡 Note:
Lake 2 rains on day 4, so we must dry it on day 2. Lake 1 rains on day 5, so we dry it on day 3. This prevents both floods.
impossible_case.py — Python
$
Input:
rains = [1, 2, 0, 1, 2]
›
Output:
[]
💡 Note:
Lake 1 is full after day 0, rains again on day 3. Lake 2 is full after day 1, rains again on day 4. Only one dry day (day 2) cannot prevent both floods.
Visualization
Tap to expand
Understanding the Visualization
1
Monitor Weather
Track which areas are flooded and when storms are coming
2
Detect Threat
Identify when a storm will hit an already flooded area
3
Deploy Crews
Use binary search to find the best time to send drainage crews
4
Prevent Disaster
Complete drainage before the next storm hits
Key Takeaway
🎯 Key Insight: Use greedy strategy with binary search - always handle the most urgent flood threat first by finding the earliest available dry day after a lake was filled.
Time & Space Complexity
Time Complexity
O(n log n)
Binary search operations on dry days for each lake
⚡ Linearithmic
Space Complexity
O(n)
Space for tracking full lakes and dry days
⚡ Linearithmic Space
Constraints
- 1 ≤ rains.length ≤ 105
- 0 ≤ rains[i] ≤ 109
- rains[i] = 0 means no rain (dry day)
- rains[i] > 0 means rain on lake rains[i]
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code