Magicsheet logo

Longest Turbulent Subarray

Medium
12.5%
Updated 8/1/2025

Longest Turbulent Subarray

What is this problem about?

The Longest Turbulent Subarray problem gives you an integer array and asks you to find the length of the longest contiguous subarray that is "turbulent." A subarray is turbulent if the comparison signs between adjacent elements flip-flop back and forth. For example, A > B < C > D < E is turbulent. It represents a zigzag pattern of peaks and valleys.

Why is this asked in interviews?

This problem is a fantastic way to test a candidate's state-tracking skills. It goes a step beyond simple "strictly increasing" or "decreasing" arrays by requiring you to alternate states. Interviewers use it to see if you can write clean, modular code that evaluates the relationship between elements (greater than, less than, equal to) and seamlessly resets chains without causing out-of-bounds errors.

Algorithmic pattern used

This problem is best solved using a Single Pass / Sliding Window (or State Machine) pattern. You iterate through the array while maintaining the length of the current turbulent sequence. You evaluate the current transition (> or <) and compare it to the previous transition. If they are different, the turbulence continues, and you increment your count. If they are the same, the zigzag breaks, and you reset the count to 2. If the elements are equal, the count resets to 1.

Example explanation

Array: [9, 4, 2, 10, 7, 8]

  • [9, 4]: 9>49 > 4. Valid. Length = 2. Prev sign: >.
  • [4, 2]: 4>24 > 2. The sign is > again! Turbulence breaks. We start a new sequence from [4, 2]. Length = 2. Prev sign: >.
  • [2, 10]: 2<102 < 10. Sign is <. It alternates from the previous >. Turbulence continues! Length = 3. Prev sign: <.
  • [10, 7]: 10>710 > 7. Alternates! Length = 4. Prev sign: >.
  • [7, 8]: 7<87 < 8. Alternates! Length = 5. The longest turbulent subarray is [4, 2, 10, 7, 8] with a length of 5.

Common mistakes candidates make

A major pitfall is improperly handling flat segments where adjacent elements are equal (e.g., [2, 2]). An equal sign breaks turbulence completely, meaning the new valid sequence length drops down to 1 (just the single element), not 2. Candidates often write if/else blocks that assume if it's not >, it must be <, forgetting the == edge case entirely.

Interview preparation tip

When tackling the Longest Turbulent Subarray coding problem, use an integer or a simple variable to track the "expected next sign" or the "previous sign" (e.g., 1 for up, -1 for down, 0 for flat). This drastically simplifies your if conditions. By comparing Integer.compare(arr[i-1], arr[i]) with your previous state, you can write a highly elegant and bug-free solution.

Similar Questions