Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the Longest Turbulent Subarray
Next article icon

Find the Longest Turbulent Subarray

Last Updated : 07 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[] of size n. A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. The task is to find the length of a maximum size turbulent subarray of arr[]. More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:

For i <= k < j:

  • arr[k] > arr[k + 1] when k is odd, and
  • arr[k] < arr[k + 1] when k is even.

Or, for i <= k < j:

  • arr[k] > arr[k + 1] when k is even, and
  • arr[k] < arr[k + 1] when k is odd.

Example:

Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]

Input: arr = [4,8,12,16]
Output: 2

Approach:

To solve this problem, we can use a sliding window approach. We maintain two pointers that define the current subarray. As we iterate through the array, we check if the current element continues the turbulent property with the previous element. If it does, we extend the window. If it does not, we reset the window. We keep track of the maximum length of such subarrays during this process.

Steps-by-step approach:

  • Initialize two pointers, start and end, both pointing to the beginning of the array.
  • Iterate through the array using the end pointer.
    • Check if the current subarray maintains the turbulent condition.
      • If it does, update the maximum length.
      • If it does not, move the start pointer to the next position and continue.
  • Return the maximum length of turbulent subarrays found.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> using namespace std;  int maxTurbulenceSize(vector<int>& arr) {     int n = arr.size();     if (n < 2) return n;      int maxLen = 1;     int start = 0;          for (int end = 1; end < n; ++end) {         int cmp = arr[end - 1] == arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);                  if (end == n - 1 || cmp * (arr[end] == arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) != -1) {             if (cmp != 0) {                 maxLen = max(maxLen, end - start + 1);             }             start = end;         }     }          return maxLen; }  int main() {     // Example 1     vector<int> arr1 = {9, 4, 2, 10, 7, 8, 8, 1, 9};     cout << maxTurbulenceSize(arr1) << endl; // Output: 5           return 0; } 
Java
//code by flutterfly public class TurbulenceSize {     public static int maxTurbulenceSize(int[] arr) {         int n = arr.length;         if (n < 2) return n;          int maxLen = 1;         int start = 0;          for (int end = 1; end < n; ++end) {             int cmp;             if (arr[end - 1] == arr[end]) {                 cmp = 0;             } else if (arr[end - 1] < arr[end]) {                 cmp = 1;             } else {                 cmp = -1;             }                          int nextCmp = 0;             if (end < n - 1) {                 if (arr[end] == arr[end + 1]) {                     nextCmp = 0;                 } else if (arr[end] < arr[end + 1]) {                     nextCmp = 1;                 } else {                     nextCmp = -1;                 }             }              if (end == n - 1 || cmp * nextCmp != -1) {                 if (cmp != 0) {                     maxLen = Math.max(maxLen, end - start + 1);                 }                 start = end;             }         }          return maxLen;     }      public static void main(String[] args) {         // Example 1         int[] arr1 = {9, 4, 2, 10, 7, 8, 8, 1, 9};         System.out.println(maxTurbulenceSize(arr1)); // Output: 5     } } 
Python
# code by flutterfly def max_turbulence_size(arr):     n = len(arr)     if n < 2:         return n      max_len = 1     start = 0          for end in range(1, n):         if arr[end - 1] == arr[end]:             cmp = 0         elif arr[end - 1] < arr[end]:             cmp = 1         else:             cmp = -1                  if end == n - 1 or cmp * (0 if arr[end] == arr[end + 1] else (1 if arr[end] < arr[end + 1] else -1)) != -1:             if cmp != 0:                 max_len = max(max_len, end - start + 1)             start = end          return max_len  if __name__ == "__main__":     # Example 1     arr1 = [9, 4, 2, 10, 7, 8, 8, 1, 9]     print(max_turbulence_size(arr1))  # Output: 5 
C#
//code by flutterfly using System;  class Program {     public static int MaxTurbulenceSize(int[] arr)     {         int n = arr.Length;         if (n < 2) return n;          int maxLen = 1;         int start = 0;                  for (int end = 1; end < n; ++end)         {             int cmp = arr[end - 1] == arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);                          if (end == n - 1 || cmp * (arr[end] == arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) != -1)             {                 if (cmp != 0)                 {                     maxLen = Math.Max(maxLen, end - start + 1);                 }                 start = end;             }         }                  return maxLen;     }      static void Main()     {         // Example 1         int[] arr1 = { 9, 4, 2, 10, 7, 8, 8, 1, 9 };         Console.WriteLine(MaxTurbulenceSize(arr1)); // Output: 5     } } 
JavaScript
//code by flutterfly function maxTurbulenceSize(arr) {     const n = arr.length;     if (n < 2) return n;      let maxLen = 1;     let start = 0;      for (let end = 1; end < n; ++end) {         let cmp = arr[end - 1] === arr[end] ? 0 : (arr[end - 1] < arr[end] ? 1 : -1);          if (end === n - 1 || cmp * (arr[end] === arr[end + 1] ? 0 : (arr[end] < arr[end + 1] ? 1 : -1)) !== -1) {             if (cmp !== 0) {                 maxLen = Math.max(maxLen, end - start + 1);             }             start = end;         }     }      return maxLen; }  // Example 1 const arr1 = [9, 4, 2, 10, 7, 8, 8, 1, 9]; console.log(maxTurbulenceSize(arr1)); // Output: 5 

Output
5 

Time Complexity: O(n), where n is the length of the array. This is because we are iterating through the array once.
Auxiliary Space: O(1) since we are using only a few extra variables to keep track of indices and the maximum length.


Next Article
Find the Longest Turbulent Subarray

T

traderjb0fy
Improve
Article Tags :
  • DSA
  • Arrays
  • sliding-window
  • Uber
Practice Tags :
  • Uber
  • Arrays
  • sliding-window

Similar Reads

    Longest Subarray with 0 Sum
    Given an array arr[] of size n, the task is to find the length of the longest subarray with sum equal to 0.Examples:Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23}Output: 5Explanation: The longest subarray with sum equals to 0 is {-2, 2, -8, 1, 7}Input: arr[] = {1, 2, 3}Output: 0Explanation: There is n
    10 min read
    Longest increasing subarray
    Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element in the same subarray. Time Complexity should be O(n). Examples: Input : arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}
    15+ min read
    Longest common subarray in the given two arrays
    Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of an equal subarray or the longest common subarray between the two given array. Examples: Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to b
    15+ min read
    Length of the longest alternating subarray
    Given an array of N including positive and negative numbers only. The task is to find the length of the longest alternating (means negative-positive-negative or positive-negative-positive) subarray present in the array. Examples: Input: a[] = {-5, -1, -1, 2, -2, -3} Output: 3 The subarray {-1, 2, -2
    5 min read
    Longest subarray having maximum sum
    Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences