Longest Turbulent Subarray
Master this topic with zero to advance depth.
Longest Turbulent Subarray
Find the maximum size of a 'turbulent' subarray where the comparison sign flips between adjacent pairs (e.g., a > b < c > d).
Visual Representation
arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]
[9 > 4] (Turbulent? Yes, Len 2)
[9 > 4 < 2] (Turbulent? No, 4 > 2 is same sign as 9 > 4)
[2 < 10 > 7 < 8] (Turbulent? Yes, Len 4)
[8 == 8] (Reset window)Examples
Level I: Brute Force
Intuition
Iterate through all possible starting points i. For each i, expand the subarray as long as it remains turbulent. Track the maximum length.
Thought Process
- Outer loop
ifrom0ton-1. - Inner loop
jstarts fromi. - Check if
arr[j...j+1]satisfies the turbulent condition based onarr[j-1...j]. - If it breaks, record length and start next
i. - Maximize the findings.
Detailed Dry Run
| i | Turbulent Subarray | Length |
|---|---|---|
| 0 | [9, 4] | 2 |
| 1 | [4, 2] | 2 |
| 2 | [2, 10, 7, 8] | 4 |
| 6 | [8, 8] | 1 |
Level III: Optimal (Sliding Window)
Intuition
Thought Process
We essentially track the 'alternating sign' property. If the comparison between arr[i-1] and arr[i] matches the alternating expectation, we expand. If they are equal, we reset. If they have the same sign as the previous pair, we slide the start to the previous element.
Patterns
- Comparison Matching: Use
Integer.compareor sign functions. - Dynamic Anchor: Move anchor point based on where turbulence breaks.
Detailed Dry Run
| i | Comparison | anchor | res |
|---|---|---|---|
| 1 | 9 > 4 (1) | 0 | 2 |
| 2 | 4 > 2 (1) | 1 | 2 |
| 3 | 2 < 10 (-1) | 2 | 2 |
| 4 | 10 > 7 (1) | 2 | 3 |
| 5 | 7 < 8 (-1) | 2 | 4 |
⚠️ Common Pitfalls & Tips
Equal elements (e.g., 8, 8) break the turbulence immediately and reset the anchor to the current index.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.