Longest Turbulent Subarray - Problem

Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:

  • For i <= k < j: arr[k] > arr[k + 1] when k - i is even, and arr[k] < arr[k + 1] when k - i is odd.
  • OR, for i <= k < j: arr[k] > arr[k + 1] when k - i is odd, and arr[k] < arr[k + 1] when k - i is even.

Input & Output

Example 1 — Basic Turbulent Array
$ Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
💡 Note: The longest turbulent subarray is [4,2,10,7,8] with pattern: 4 > 2 < 10 > 7 < 8, length = 5
Example 2 — All Equal Elements
$ Input: arr = [4,4,4]
Output: 1
💡 Note: All elements are equal, so no turbulent subarray exists beyond single elements
Example 3 — Two Elements
$ Input: arr = [100,1]
Output: 2
💡 Note: A subarray of length 2 with different elements is turbulent: 100 > 1

Constraints

  • 1 ≤ arr.length ≤ 4 × 104
  • 0 ≤ arr[i] ≤ 109

Visualization

Tap to expand
Longest Turbulent Subarray Problem9421078819><<><=><Longest Turbulent: 4>2<10>7<8Pattern breaks at 8=8, then continuesOutput: Length = 5
Understanding the Visualization
1
Input Array
Array with elements to check for turbulent pattern
2
Find Pattern
Look for alternating > and < comparisons
3
Return Length
Length of longest turbulent subarray
Key Takeaway
🎯 Key Insight: Use dynamic programming to track sequences ending with increasing/decreasing patterns for O(n) solution
Asked in
Amazon 35 Google 28 Microsoft 22
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen