Ctrl K

Nights of the Withering Row

Medium
Seedlings are planted in a row, and their heights from left to right are given in the array heights. Every night, each seedling that is **strictly shorter** than its left neighbour (the nearest one still in the row) withers. All such seedlings wither at the same time, and in the morning the row closes up: the withered ones are removed and the survivors get new neighbours. How many nights pass before the row stops changing, that is, before the heights from left to right become non-decreasing? If the row is already like that, the answer is 0. A direct night-by-night simulation can take O(n²); try to do it in O(n).
Example 1
heights=[6, 2, 4, 1, 7] → 2

On the first night 2 (next to 6) and 1 (next to 4) wither, leaving [6, 4, 7]. On the second night 4 (next to 6) withers, leaving [6, 7], which never changes again. The answer is 2.

Example 2
heights=[1, 3, 3, 8] → 0

No plant is shorter than its left neighbour, so the row is already settled.

Example 3
heights=[9, 1, 2, 3] → 3

Exactly one plant withers each night: first 1, then 2, then 3, since each time the new neighbour of 9 is shorter than it.

Constraints
  • 1 ≤ len(heights) ≤ 10⁵
  • 1 ≤ heights[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNext Larger Down the List MediumPreorder of a Search Tree MediumLow, Peak, Middle MediumNext Larger Around the Circle MediumFix the Middle of the Line Medium
loading Python…
Input
heights=[6, 2, 4, 1, 7]
Expected
2

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