Skip to content
Problem 978 · LeetCode 978(opens in a new tab)

Longest Turbulent Subarray

MediumArrays

You get an integer array arr. A run of neighbouring elements is turbulent when the comparisons between consecutive elements keep switching direction: up, down, up, … or down, up, down, …. Two equal neighbours are never allowed inside a turbulent run.

Return the length of the longest turbulent subarray. A single element counts as a turbulent subarray of length 1.

Example 1

Input:  arr = [3, 8, 2, 5, 5, 1, 6]
Output: 4
Why:    3 < 8 > 2 < 5 switches direction every step
2 more examples and the constraints

Example 2

Input:  arr = [2, 5, 9, 11]
Output: 2
Why:    it only rises, so any two neighbours are the best

Example 3

Input:  arr = [7]
Output: 1
Why:    one element on its own

Constraints

  • 1 ≤ arr.length ≤ 40,000
  • 0 ≤ arr[i] ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Grow from every startO(n²)
  2. One pass, running lengthO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 40,000 numbersVerdict
Grow from every startO(n²)
Correct, too slow at the limit
One pass, running lengthO(n)
Best; one pass, three numbers

n = length of arr.

Edge cases to test

  • One element. [7] returns 1.
  • All equal. [6, 6, 6] returns 1: equal neighbours never form a longer run.
  • Only rising or only falling. Any two different neighbours make a run of 2.
  • A flat step after a flat step. The first different pair after it must restart at 2, not grow from an old direction.

Common mistakes

  • Starting the answer at 0 instead of 1, so a single element or all-equal array returns 0.
  • Treating a flat step like a direction change and growing the run across equal neighbours.
  • Resetting the run to 1 instead of 2 when the direction repeats: the last pair is still a valid run.

How to talk through it

  1. 1Clarify. Does one element count? What happens with equal neighbours?
  2. 2Give the brute force. Grow a window from every start; O(n²), too slow for 40,000 zigzag numbers.
  3. 3Find the local rule. The run ending at i depends only on the step into i and the step before it.
  4. 4Code the one pass. Flat: 1. Flipped: grow. Same direction: 2. Keep the best.
  5. 5Test out loud. Run [7], [6, 6, 6] and an array with a flat step in the middle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?