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
๐ŸŽข Turbulence Visualization421078819๐ŸŽฏ Turbulent Section: Length 54 > 2 < 10 > 7 < 8โ†“ โ†‘ โ†“ โ†‘ (Perfect alternating pattern!)Broken by equal elements 8=8, then continues...State Evolution:inc=1, dec=1 โ†’ Process 4>2: inc=1, dec=2โ†’ Process 2<10: inc=3, dec=1โ†’ Process 10>7: inc=1, dec=4โ†’ Process 7<8: inc=5, dec=1 โœจ MAX!
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!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~18 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