Ctrl K

A Plan for Draining Ponds

Medium
A park has infinitely many ponds numbered from 1, and all of them start empty. The forecast forecast goes day by day: forecast[i] > 0 means that on day i rain fills the pond with that number, and forecast[i] == 0 means a dry day on which you may drain any one pond. If rain falls on a pond that is already full, it overflows. Build a plan plan of the same length: on rainy days plan[i] = -1, and on dry days it is the number of the pond being drained. To make the answer unique, build the plan this way. Go through the days in order. When rain comes back to a pond that was filled on day p, give that pond the earliest dry day after p that has not been taken yet; if there is no such day, an overflow cannot be avoided, so return an empty array. Dry days that end up unused go to pond 1 (draining an empty pond is allowed and changes nothing). Try to avoid a quadratic scan over the dry days.
Example 1
forecast=[3, 0, 5, 0, 3, 5] → [-1, 3, -1, 5, -1, -1]

Rain over pond 3 returns on day 4, so it is drained on the first free dry day after day 0, which is day 1. Pond 5 (rain on days 2 and 5) gets day 3. The answer is [-1, 3, -1, 5, -1, -1].

Example 2
forecast=[2, 0, 0, 7] → [-1, 1, 1, -1]

No pond gets rain twice, so the dry days are not needed and, by the rule, pond 1 is drained on them.

Example 3
forecast=[4, 6, 0, 4, 6] → []

The only dry day goes to pond 4, and pond 6 overflows on day 4. The answer is an empty array.

Constraints
  • 1 ≤ len(forecast) ≤ 10⁵
  • 0 ≤ forecast[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsJobs With a Cooldown MediumSorted Into Runs of Three MediumSpread Out the Labels MediumCross Out Half the List MediumPrices That Fade With Each Sale Medium
loading Python…
Input
forecast=[3, 0, 5, 0, 3, 5]
Expected
[-1, 3, -1, 5, -1, -1]

Run checks the first 3 tests in your browser. Submit checks all 245 tests on the server, hidden ones included.