#978

Longest Turbulent Subarray

Medium
ArrayDynamic ProgrammingSliding WindowSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass through the array to track the length of the current turbulent subarray. This is more efficient because we only need to check adjacent elements, rather than all possible subarrays.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two variables to track the current length of turbulent subarray and the maximum length found.
  2. 2Step 2: Iterate through the array, comparing adjacent elements to determine if they form a turbulent pair.
  3. 3Step 3: If they do, increase the current length. If not, reset the current length to 1.
  4. 4Step 4: Update the maximum length whenever the current length exceeds it.
solution.py16 lines
1# Full working Python code
2
3def maxTurbulenceSize(arr):
4    n = len(arr)
5    if n < 2:
6        return n
7    max_length = 1
8    current_length = 1
9    for i in range(1, n):
10        if (arr[i - 1] < arr[i] and (i % 2 == 1)) or (arr[i - 1] > arr[i] and (i % 2 == 0)):
11            current_length += 1
12        else:
13            current_length = 2 if arr[i - 1] != arr[i] else 1
14        max_length = max(max_length, current_length)
15    return max_length
16

Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1The pattern of comparisons is crucial for identifying turbulent subarrays.
  • 2Tracking the length of the current turbulent subarray allows for efficient updates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.