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 INPUT arr = [9,4,2,10,7,8,8,1,9] 9 4 2 10 7 8 8 1 9 Turbulent Pattern: Sign alternates: > < > < > < Indices: 0 to 8 (length 9) Green = longest turbulent subarray (indices 2-6) ALGORITHM STEPS 1 Initialize up=1, down=1, maxLen=1 2 Iterate Array Compare adjacent pairs 3 Update Counters If a[i]>a[i-1]: up=down+1 If a[i]<a[i-1]: down=up+1 4 Track Maximum maxLen = max(up, down) State Transitions i=1: 9>4 up=1 dn=2 i=2: 4>2 up=1 dn=2 i=3: 2<10 up=3 dn=1 i=4: 10>7 up=1 dn=4 i=5: 7<8 up=5 dn=1 FINAL RESULT Longest Turbulent Subarray: [2, 10, 7, 8, 8] Pattern: 2 < 10 > 7 < 8 = 8 2 10 7 8 8 Output: 5 OK - Length = 5 Indices 2 to 6 Key Insight: Use two counters (up, down) to track alternating sequences. When arr[i] > arr[i-1], extend the "down" sequence. When arr[i] < arr[i-1], extend the "up" sequence. Reset both when equal. Time: O(n), Space: O(1) - Single pass with constant extra space. TutorialsPoint - Longest Turbulent Subarray | Optimal 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