# Length of the longest alternating even odd subarray

• Difficulty Level : Easy
• Last Updated : 29 Sep, 2022

Given an array a[] of N integers, the task is to find the length of the longest Alternating Even Odd subarray present in the array.

Examples:

Input: a[] = {1, 2, 3, 4, 5, 7, 9}
Output:
Explanation:
The subarray {1, 2, 3, 4, 5} has alternating even and odd elements.

Input: a[] = {1, 3, 5}
Output:
Explanation:
There is no such alternating sequence possible.

## Naive approach:

The idea is to consider every subarray and find the length of even and odd subarrays.

Follow the steps below to solve the problem:

• Iterate for every subarray from i = 0
• Make a nested loop, iterate from j = i + 1
• Now, check if a[j – 1] is even and a[j] is odd or a[j – 1] is odd and a[j] is even then increment count
• Maintain an answer variable which calculates max count so far

Below is the implementation of the above approach:

## C++

 `#include ``using` `namespace` `std;` `// Function to find the longest subarray``int` `longestEvenOddSubarray(``int` `a[], ``int` `n)``{``    ``// Length of longest``    ``// alternating subarray``    ``int` `ans = 1;` `    ``// Iterate in the array``    ``for` `(``int` `i = 0; i < n; i++) {``        ``int` `cnt = 1;``        ``// Iterate for every  subarray``        ``for` `(``int` `j = i + 1; j < n; j++) {``            ``if` `((a[j - 1] % 2 == 0 && a[j] % 2 != 0)``                ``|| (a[j - 1] % 2 != 0 && a[j] % 2 == 0))``                ``cnt++;``            ``else``                ``break``;``        ``}``        ``// store max count``        ``ans = max(ans, cnt);``    ``}``    ``// Length of 'ans' can never be 1``    ``// since even odd has to occur in pair or more``    ``// so return 0 if ans = 1``    ``if` `(ans == 1)``        ``return` `0;``    ``return` `ans;``}` `/* Driver code*/``int` `main()``{``    ``int` `a[] = { 1, 2, 3, 4, 5, 7, 8 };` `    ``int` `n = ``sizeof``(a) / ``sizeof``(a);` `    ``cout << longestEvenOddSubarray(a, n);``    ``return` `0;``}`

## Java

 `// Java program for above approach``import` `java.io.*;``import` `java.util.ArrayList;``import` `java.util.List;` `// Function to check if it is possible``// to make the array elements consecutive``public` `class` `GfG {` `    ``// Function to find the longest subarray``    ``static` `int` `longestEvenOddSubarray(ArrayList a,``                                      ``int` `n)``    ``{` `        ``// Length of longest``        ``// alternating subarray``        ``int` `ans = ``1``;` `        ``// Iterate in the array``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``int` `cnt = ``1``;` `            ``// Iterate for every subarray``            ``for` `(``int` `j = i + ``1``; j < n; j++) {``                ``if` `((a.get(j - ``1``) % ``2` `== ``0``                     ``&& a.get(j) % ``2` `!= ``0``)``                    ``|| (a.get(j - ``1``) % ``2` `!= ``0``                        ``&& a.get(j) % ``2` `== ``0``))``                    ``cnt++;``                ``else``                    ``break``;``            ``}` `            ``// store max count``            ``ans = Math.max(ans, cnt);``        ``}` `        ``// Length of 'ans' can never be 1``        ``// since even odd has to occur in pair or more``        ``// so return 0 if ans = 1``        ``if` `(ans == ``1``)``            ``return` `0``;``        ``return` `ans;``    ``}` `    ``// Drivers code``    ``public` `static` `void` `main(String args[])``    ``{``        ``ArrayList a = ``new` `ArrayList(``            ``List.of(``1``, ``2``, ``3``, ``4``, ``5``, ``7``, ``8``));``        ``int` `n = a.size();``        ``System.out.println(longestEvenOddSubarray(a, n));``    ``}``}` `// This code is contributed by shinjanpatra`

## Python3

 `import` `math` `# Function to find the longest subarray`  `def` `longestEvenOddSubarray(a, n):` `    ``# Length of longest``    ``# alternating subarray``    ``ans ``=` `1` `    ``# Iterate in the array``    ``for` `i ``in` `range``(n):``        ``cnt ``=` `1` `        ``# Iterate for every  subarray``        ``for` `j ``in` `range``(i ``+` `1``, n):``            ``if` `((a[j ``-` `1``] ``%` `2` `=``=` `0` `and` `a[j] ``%` `2` `!``=` `0``)``                    ``or` `(a[j ``-` `1``] ``%` `2` `!``=` `0` `and` `a[j] ``%` `2` `=``=` `0``)):``                ``cnt ``=` `cnt``+``1``            ``else``:``                ``break``        ``# store max count``        ``ans ``=` `max``(ans, cnt)` `    ``# Length of 'longest' can never be 1 since``    ``# even odd has to occur in pair or more``    ``# so return 0 if longest = 1``    ``if``(ans ``=``=` `1``):``        ``return` `0``    ``return` `ans`  `# Driver code``a ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``7``, ``8``]` `n ``=` `len``(a)` `print``(longestEvenOddSubarray(a, n))` `# This code is contributed by shinjanpatra.`

## C#

 `// C# program for above approach``using` `System;``using` `System.Collections.Generic;` `// Function to check if it is possible``// to make the array elements consecutive``public` `class` `GfG {` `  ``// Function to find the longest subarray``  ``static` `int` `longestEvenOddSubarray(List<``int``> a, ``int` `n)``  ``{` `    ``// Length of longest``    ``// alternating subarray``    ``int` `ans = 1;` `    ``// Iterate in the array``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int` `cnt = 1;` `      ``// Iterate for every subarray``      ``for` `(``int` `j = i + 1; j < n; j++) {``        ``if` `((a[j - 1] % 2 == 0 && a[j] % 2 != 0)``            ``|| (a[j - 1] % 2 != 0 && a[j] % 2 == 0))``          ``cnt++;``        ``else``          ``break``;``      ``}` `      ``// store max count``      ``ans = Math.Max(ans, cnt);``    ``}` `    ``// Length of 'ans' can never be 1``    ``// since even odd has to occur in pair or more``    ``// so return 0 if ans = 1``    ``if` `(ans == 1)``      ``return` `0;``    ``return` `ans;``  ``}` `  ``// Drivers code``  ``public` `static` `void` `Main(``string``[] args)``  ``{``    ``List<``int``> a = ``new` `List<``int``>{ 1, 2, 3, 4, 5, 7, 8 };``    ``int` `n = a.Count;``    ``Console.WriteLine(longestEvenOddSubarray(a, n));``  ``}``}` `// This code is contributed by phasing17`

## Javascript

 ``

Output

`5`

Time Complexity: O(N2), Iterating over every subarray therefore N2 are possible
Auxiliary Space: O(1)

## Length of the longest alternating even odd subarray by Checking Parity of Sum:

Observe that the Sum of two even numbers is even, the Sum of two odd numbers is even but the sum of one even and one odd number is odd.

Follow the steps below to solve the problem:

• Initially initialize cnt a counter to store the length as 1.
• Iterate among the array elements, and check if consecutive elements have an odd sum.
• Increase the cnt by 1 if it has an odd sum.
• If it does not has an odd sum, then re-initialize cnt by 1.

Below is the implementation of the above approach:

## C++

 `// C++ program to find the Length of the``// longest alternating even odd subarray` `#include ``using` `namespace` `std;` `// Function to find the longest subarray``int` `longestEvenOddSubarray(``int` `arr[], ``int` `n)``{``    ``// Length of longest``    ``// alternating subarray` `    ``int` `count = 1;``    ``int` `maxcount = 1;``    ``for` `(``int` `i = 0; i < n - 1; i++) {``        ``if` `(arr[i] % 2 == 0 && arr[i + 1] % 2 != 0) {``            ``count++;``        ``}``        ``if` `(arr[i] % 2 != 0 && arr[i + 1] % 2 == 0) {``            ``count++;``        ``}``        ``if` `(arr[i] % 2 == 0 && arr[i + 1] % 2 == 0) {``            ``count = 1;``        ``}``        ``if` `(arr[i] % 2 != 0 && arr[i + 1] % 2 != 0) {``            ``count = 1;``        ``}``        ``maxcount = max(maxcount, count);``    ``}``    ``// Length of 'maxcount' can never be 1``    ``// since even odd has to occur in pair or more``    ``// so return 0 if maxcount = 1``    ``if` `(maxcount == 1)``        ``return` `0;``    ``return` `maxcount;``}` `/* Driver code*/``int` `main()``{``    ``int` `arr[] = { 1, 2, 3, 4, 5, 7, 8 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``cout << longestEvenOddSubarray(arr, n);``    ``return` `0;``}`

## Java

 `// Java program to find the Length of the``// longest alternating even odd subarray``import` `java.util.*;``class` `GFG {` `    ``// Function to find the longest subarray``    ``static` `int` `longestEvenOddSubarray(``int` `a[], ``int` `n)``    ``{``        ``// Length of longest``        ``// alternating subarray``        ``int` `longest = ``1``;``        ``int` `cnt = ``1``;` `        ``// Iterate in the array``        ``for` `(``int` `i = ``0``; i < n - ``1``; i++) {` `            ``// increment count if consecutive``            ``// elements has an odd sum``            ``if` `((a[i] + a[i + ``1``]) % ``2` `== ``1``) {``                ``cnt++;``            ``}``            ``else` `{``                ``// Store maximum count in longest``                ``longest = Math.max(longest, cnt);` `                ``// Reinitialize cnt as 1 consecutive``                ``// elements does not have an odd sum``                ``cnt = ``1``;``            ``}``        ``}` `        ``// Length of 'longest' can never be 1``        ``// since even odd has to occur in pair or more``        ``// so return 0 if longest = 1``        ``if` `(longest == ``1``)``            ``return` `0``;` `        ``return` `Math.max(cnt, longest);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `a[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``7``, ``8` `};` `        ``int` `n = a.length;` `        ``System.out.println(longestEvenOddSubarray(a, n));``    ``}``}` `// This code is contributed by offbeat`

## Python3

 `# Python3 program to find the length of the``# longest alternating even odd subarray` `# Function to find the longest subarray`  `def` `longestEvenOddSubarray(arr, n):` `    ``# Length of longest``    ``# alternating subarray``    ``longest ``=` `1``    ``cnt ``=` `1` `    ``# Iterate in the array``    ``for` `i ``in` `range``(n ``-` `1``):` `        ``# Increment count if consecutive``        ``# elements has an odd sum``        ``if``((arr[i] ``+` `arr[i ``+` `1``]) ``%` `2` `=``=` `1``):``            ``cnt ``=` `cnt ``+` `1``        ``else``:` `            ``# Store maximum count in longest``            ``longest ``=` `max``(longest, cnt)` `            ``# Reinitialize cnt as 1 consecutive``            ``# elements does not have an odd sum``            ``cnt ``=` `1` `    ``# Length of 'longest' can never be 1 since``    ``# even odd has to occur in pair or more``    ``# so return 0 if longest = 1``    ``if``(longest ``=``=` `1``):``        ``return` `0` `    ``return` `max``(cnt, longest)`  `# Driver Code``arr ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``7``, ``8``]``n ``=` `len``(arr)` `print``(longestEvenOddSubarray(arr, n))` `# This code is contributed by skylags`

## C#

 `// C# program to find the Length of the``// longest alternating even odd subarray``using` `System;` `class` `GFG {` `    ``// Function to find the longest subarray``    ``static` `int` `longestEvenOddSubarray(``int``[] a, ``int` `n)``    ``{` `        ``// Length of longest``        ``// alternating subarray``        ``int` `longest = 1;``        ``int` `cnt = 1;` `        ``// Iterate in the array``        ``for` `(``int` `i = 0; i < n - 1; i++) {` `            ``// Increment count if consecutive``            ``// elements has an odd sum``            ``if` `((a[i] + a[i + 1]) % 2 == 1) {``                ``cnt++;``            ``}``            ``else` `{` `                ``// Store maximum count in longest``                ``longest = Math.Max(longest, cnt);` `                ``// Reinitialize cnt as 1 consecutive``                ``// elements does not have an odd sum``                ``cnt = 1;``            ``}``        ``}` `        ``// Length of 'longest' can never be 1``        ``// since even odd has to occur in pair``        ``// or more so return 0 if longest = 1``        ``if` `(longest == 1)``            ``return` `0;``        ``return` `Math.Max(cnt, longest);``    ``}` `    ``// Driver code``    ``static` `void` `Main()``    ``{` `        ``int``[] a = { 1, 2, 3, 4, 5, 7, 8 };``        ``int` `n = a.Length;` `        ``Console.WriteLine(longestEvenOddSubarray(a, n));``    ``}``}` `// This code is contributed by divyeshrabadiya07`

## Javascript

 ``

Output

`5`

Time Complexity: O(N), Traversing over the array one time.
Auxiliary Space: O(1)

## Length of the longest alternating even odd subarray by Storing the previous element

By simply storing the nature of the previous element we encounter( odd or even) and comparing it with the next element.

Follow the steps below to solve the problem:

• Store nature of first element in a variable, i.e. if it is even or odd. (this variable will store nature of previous element)
• Now iterate over the array from index 1 to n – 1 and keep checking if the nature(odd/even) of current index is not same to as that of previous number.
• Keep storing the max_length of subarray whenever the length of subarray exceeds value to previously found max subarray.
• Return the found max length of subarray.

Below is the implementation of above approach:

## C++

 `// C++ code to find longest subarray of alternating even and``// odds` `#include ``using` `namespace` `std;` `int` `maxEvenOdd(``int` `arr[], ``int` `n)``{``    ``if` `(n == 0)``        ``return` `0;` `    ``int` `maxLength = 0;``    ``// storing the nature of first element, if``    ``// remainder = 1, it is odd``    ``bool` `prevOdd = arr % 2;``    ``int` `curLength = 1;` `    ``for` `(``int` `i = 1; i < n; i++) {``        ``// everytime we check if previous``        ``// element has opposite even/odd``        ``// nature or not``        ``if` `(arr[i] % 2 != prevOdd)``            ``curLength++;``        ``else``            ``// reset value when pattern is broken``            ``curLength = 1;``        ``// changing value  when new maximum``        ``// subarray is found``        ``if` `(curLength > maxLength)``            ``maxLength = curLength;` `        ``// updating even/odd nature of prev``        ``// number encountered everytime``        ``prevOdd = arr[i] % 2;``    ``}` `    ``return` `maxLength;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 1, 2, 3, 4, 5, 3, 7, 2, 9, 4 };``    ``// longest subarray should be 1 2 3 4 5 , therefore``    ``// length = 5``    ``int` `n = ``sizeof``(arr) / ``sizeof``(``int``);``    ``cout << ``"Length of longest subarray of even and odds "``            ``"is : "``         ``<< maxEvenOdd(arr, n);` `    ``return` `0;``}` `// this code is contributed by Anshit Bansal`

## C#

 `// C# code to find longest subarray``// of alternating even and odds``using` `System;` `public` `class` `GFG {` `  ``public` `static` `int` `maxEvenOdd(``int``[] arr, ``int` `n)``  ``{``    ``if` `(n == 0)``      ``return` `0;` `    ``int` `maxLength = 0;` `    ``// storing the nature of first element, if``    ``// remainder = 1, it is odd``    ``int` `prevOdd = arr % 2;``    ``int` `curLength = 1;``    ``for` `(``int` `i = 1; i < n; i++)``    ``{` `      ``// everytime we check if previous``      ``// element has opposite even/odd``      ``// nature or not``      ``if` `(arr[i] % 2 != prevOdd)``        ``curLength++;``      ``else` `        ``// reset value when pattern is broken``        ``curLength = 1;` `      ``// changing value  when new maximum``      ``// subarray is found``      ``if` `(curLength > maxLength)``        ``maxLength = curLength;` `      ``// updating even/odd nature of prev``      ``// number encountered everytime``      ``prevOdd = arr[i] % 2;``    ``}` `    ``return` `maxLength;``  ``}` `  ``static` `public` `void` `Main()``  ``{` `    ``int``[] arr = { 1, 2, 3, 4, 5, 3, 7, 2, 9, 4 };` `    ``// longest subarray should be 1 2 3 4 5 , therefore``    ``// length = 5``    ``int` `n = arr.Length;``    ``Console.Write(``      ``"Length of longest subarray of even and odds is : "``);``    ``Console.Write(maxEvenOdd(arr, n));``  ``}``}` `// This code is contributed by akashish__`

## Javascript

 `// JS code to find longest subarray of alternating even and``// odds` `function` `maxEvenOdd(arr, n)``{``    ``if` `(n == 0)``        ``return` `0;` `    ``let maxLength = 0;``    ``// storing the nature of first element, if``    ``// remainder = 1, it is odd``    ``let prevOdd = arr % 2;``    ``let curLength = 1;` `    ``for` `(``var` `i = 1; i < n; i++) {``        ``// everytime we check if previous``        ``// element has opposite even/odd``        ``// nature or not``        ``if` `(arr[i] % 2 != prevOdd)``            ``curLength++;``        ``else``            ``// reset value when pattern is broken``            ``curLength = 1;``        ``// changing value  when new maximum``        ``// subarray is found``        ``if` `(curLength > maxLength)``            ``maxLength = curLength;` `        ``// updating even/odd nature of prev``        ``// number encountered everytime``        ``prevOdd = arr[i] % 2;``    ``}` `    ``return` `maxLength;``}` `// Driver Code``let arr = [ 1, 2, 3, 4, 5, 3, 7, 2, 9, 4 ];` `// longest subarray should be 1 2 3 4 5 , therefore``// length = 5``let n = arr.length;``console.log(``"Length of longest subarray of even and odds is : "` `+``         ``maxEvenOdd(arr, n));`  `// this code is contributed by phasing17`

Output

`Length of longest subarray of even and odds is : 5`

Time Complexity: O(N), Since we need to iterate over the whole array once
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up