Ctrl K

Longest Seesaw

Easy
You are given an integer array heights. Call a contiguous stretch of the array a **seesaw** if it has at least 2 elements and looks like a, a+1, a, a+1, …: the value goes up by exactly 1, then down by exactly 1, then up by 1 again, and so on, taking turns. Return the length of the longest seesaw in the array, or -1 if there is none.
Example 1
heights=[7, 5, 6, 5, 6, 5, 9] → 5

The stretch [5, 6, 5, 6, 5] alternates between 5 and 6 and starts with the smaller one, so its length is 5.

Example 2
heights=[3, 2, 3, 4] → 2

[2, 3] works, but [3, 2, 3] does not, since the stretch has to start by going up. [2, 3, 4] fails too: a step up must be followed by a step down. The answer is 2.

Example 3
heights=[4, 4, 1] → -1

No pair of neighbours goes up by exactly 1, so the answer is -1.

Constraints
  • 2 ≤ len(heights) ≤ 100
  • 1 ≤ heights[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsConsistent Reading Triples EasyRepeated Block Run EasyXOR of Every Subset EasyThree Addends and a Later Total EasyEven Numbers From Digit Cards Easy
loading Python…
Input
heights=[7, 5, 6, 5, 6, 5, 9]
Expected
5

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