Avoid Flood in The City

Your country has 10^9 lakes. Initially, all lakes are empty, but when it rains over the n^th lake, the n^th 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 every lake.

Given an integer array rains where:

  • rains[i] > 0 means there will be rain over lake rains[i].
  • rains[i] == 0 means there is no rain 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 on the i^th day if rains[i] == 0.

If there are multiple valid answers, return any of them. If it is impossible to avoid a flood, return an empty array.

Notice that if you choose to dry a full lake, it becomes empty, but if you choose to dry an empty lake, nothing changes.

Example 1
Inputrains = [1,2,3,4]
Output[-1,-1,-1,-1]
There is no day to dry any lake, but each lake is rained on only once, so no flood occurs.
Example 2
Inputrains = [1,2,0,0,2,1]
Output[-1,-1,2,1,-1,-1]
Drying lake 2 on the third day and lake 1 on the fourth day prevents both lakes from flooding when it rains on them again.

Constraints

  • 1 <= rains.length <= 10^5
  • 0 <= rains[i] <= 10^9

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate