Ctrl K

Stretches Led by Their Minimum

Hard
A sensor recorded a series of readings levels. Call a contiguous stretch of the series *stable* if its first reading is no greater than any other reading in that stretch. Count the non-empty stable stretches. Stretches with different boundaries count separately even when their values match. A single-element stretch is always stable. Checking every stretch takes O(n²); aim for something faster.
Example 1
levels=[3, 5, 4, 1] → 6

The valid stretches are [3], [5], [4], [1], [3, 5] and [3, 5, 4]; [5, 4] fails because 4 < 5. That makes 6.

Example 2
levels=[7, 7] → 3

[7], [7] and [7, 7]: equal values are allowed, so there are 3.

Example 3
levels=[9, 6, 2] → 3
Constraints
  • 1 ≤ len(levels) ≤ 5·10⁴
  • 0 ≤ levels[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardBiggest Rectangle Under the Skyline HardBiggest Solid Panel Block HardLargest Number From Two Rows HardSorting Batches With Repeats Hard
loading Python…
Input
levels=[3, 5, 4, 1]
Expected
6

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