KatInterview

Rounds of Pruning in a Garden Row

Stacks & QueuesAuto-graded · 21 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stacksimulationarrays

Last updated

Count how many rounds of simultaneous removals occur in a row of numbers where each element larger than its left neighbor is removed, using a monotonic stack to beat quadratic simulation.

A gardener has a row of shrubs, and each shrub carries an integer toxin reading. The shrubs are listed from left to right in an array.

Process

The row is pruned in rounds:

  • In a round, every shrub whose reading is strictly larger than the reading of the shrub directly to its left (in the row as it stands at the start of that round) is marked for removal.
  • All marked shrubs are removed at the same moment, at the end of the round.
  • The first shrub in the row has no left neighbor, so it is never removed.
  • Rounds continue until a round in which no shrub is removed.

Task

Given the array readings, return the number of rounds in which at least one shrub is removed. In other words, return the number of days after which the row no longer changes (the final round with no removals is not counted).

Shrubs with equal readings do not remove each other, since the comparison is strict.

Input

  • readings: a list of integers, the toxin readings from left to right.

Output

  • An integer: the number of rounds in which at least one shrub is removed.

Constraints

  • 1 <= len(readings) <= 10^5
  • 0 <= readings[i] <= 10^9
  • A solution that is faster than O(n^2) is expected.

Examples

Example 1

Input: pruning_rounds([6, 5, 8, 4, 7, 10, 9])

Output: 2

Hints

Hint 1

Simulating round by round can take about n rounds of O(n) work each. Think about computing, for each shrub, the round in which it is removed, then taking the maximum.

Hint 2

For a shrub, look at the nearest shrub on its left with a strictly smaller reading. If none exists, it is never removed. Otherwise it can only be removed after every shrub between them is gone.

Hint 3

Use a monotonic stack storing (reading, removal round). Pop entries with reading >= the current one while tracking the largest removal round among them; if the stack is still non-empty, the current removal round is that maximum plus one, else 0.