Skip to main content

Longest Turbulent Subarray

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Greedy
Sliding Window

Given an integer array arr, a subarray is a contiguous, non-empty portion of the array. A subarray is turbulent when each pair of neighboring values alternates between a strict increase and a strict decrease: the comparisons must follow either > then < then > and so on, or < then > then < and so on. Equal neighboring values do not satisfy the condition.

A subarray containing one value is considered turbulent. Return the length of the longest turbulent subarray of arr.

Example 1:

Input: arr = [5]
Output: 1
Explanation: A single-element subarray is turbulent, so the answer is 1.

Example 2:

Input: arr = [7,2,6,3,8]
Output: 5
Explanation: The comparisons are >, <, >, <, so the entire array is turbulent.

Example 3:

Input: arr = [4,4,2,2,9]
Output: 2
Explanation: Equal neighboring values break turbulence. The longest valid subarrays are pairs such as [4,2] or [2,9], each of length 2.

Constraints:

  • 1 <= arr.length <= 4 * 10^4
  • 0 <= arr[i] <= 10^9
  • ``arr contains integers

Need help or want more practice?

Practise in an interviewGet AI Coach help