Ctrl K

Steady Stretches of Readings

Medium
A sensor produced a sequence of readings readings. Call a contiguous stretch of readings **steady** if any two values in it differ by at most 2, that is, its maximum minus its minimum is at most 2. Return the number of steady stretches. Stretches with the same values at different positions count separately, and a single reading is a stretch too.
Example 1
readings=[6, 8, 7, 3] → 7

The 4 single readings qualify, as do the pairs [6, 8] and [8, 7] and the triple [6, 8, 7] (spread 2). Anything pairing 3 with a neighbor fails. Total 7.

Example 2
readings=[4, 4, 4] → 6

All 6 stretches consist of equal values, so the spread is 0.

Example 3
readings=[1, 5, 9] → 3
Constraints
  • 1 ≤ len(readings) ≤ 10⁵
  • 1 ≤ readings[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Tight-Range Stretch MediumA Dark Gap Between Street Lamps HardMoving Window Maximum HardShortest Stretch Reaching a Total HardMaximum Sum With Short Hops Hard
loading Python…
Input
readings=[6, 8, 7, 3]
Expected
7

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