Longest Turbulent Subarray - Problem
Imagine a turbulent flight where the plane alternates between climbing and descending rapidly. In this problem, we're looking for the longest "turbulent" sequence in an integer array!
Given an integer array arr, return the length of the longest turbulent subarray. A subarray is turbulent if the comparison signs alternate between adjacent elements - like a rollercoaster that goes up, then down, then up again!
What makes a subarray turbulent?
- The inequality signs must flip between each pair:
arr[i] < arr[i+1] > arr[i+2] < arr[i+3]... - Or the opposite pattern:
arr[i] > arr[i+1] < arr[i+2] > arr[i+3]... - Equal adjacent elements break the turbulence!
Example: In [9,4,2,10,7,8,8,1,9], the longest turbulent subarray is [4,2,10,7,8] with length 5, because: 4 > 2 < 10 > 7 < 8 (signs alternate perfectly!)
Input & Output
example_1.py โ 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 alternating pattern: 4 > 2 < 10 > 7 < 8. The equal elements at 8,8 break the turbulence.
example_2.py โ Single Element
$
Input:
arr = [4,8,12,16]
โบ
Output:
2
๐ก Note:
No turbulence possible since all comparisons are increasing: 4 < 8 < 12 < 16. Maximum turbulent length is 2 (any two adjacent elements).
example_3.py โ All Equal Elements
$
Input:
arr = [100]
โบ
Output:
1
๐ก Note:
Single element array has length 1. No comparisons possible, so the turbulent subarray is just the element itself.
Constraints
- 1 โค arr.length โค 4 ร 104
- 0 โค arr[i] โค 109
- Adjacent equal elements break turbulence
- Minimum turbulent subarray length is 1
Visualization
Tap to expand
Understanding the Visualization
1
Set up trackers
Initialize counters for sequences ending with climbs (inc) and drops (dec)
2
Process each elevation change
For climbs: extend previous drop sequence; For drops: extend previous climb sequence
3
Handle flat sections
Equal elevations break turbulence - reset both counters to 1
4
Track the record
Keep updating the maximum turbulent sequence length seen
Key Takeaway
๐ฏ Key Insight: By maintaining two state variables (inc/dec), we can track all possible turbulent sequences in just one pass, making this an elegant O(n) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code