Length of the longest alternating even odd subarray
Last Updated :
12 Jul, 2025
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: 5
Explanation:
The subarray {1, 2, 3, 4, 5} has alternating even and odd elements.
Input: a[] = {1, 3, 5}
Output: 0
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 <iostream>
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[0]);
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<Integer> 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<Integer> a = new ArrayList<Integer>(
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
Python
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
<script>
// Function to find the longest subarray
function longestEvenOddSubarray(a, n)
{
// Length of longest
// alternating subarray
let ans = 1;
// Iterate in the array
for (let i = 0; i < n ; i++) {
let cnt = 1;
// Iterate for every subarray
for (let 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;
}
/* Driver code*/
let a = [ 1, 2, 3, 4, 5, 7, 8 ];
let n = a.length;
document.write(longestEvenOddSubarray(a, n),"</br>");
// This code is contributed by shinjanpatra.
</script>
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.
- The function should return at least value 1 if there are elements in the array, because there can always be a subarray with length 1 which has either odd or even element.
Below is the implementation of the above approach:
C++
// C++ program to find the Length of the
// longest alternating even odd subarray
#include <bits/stdc++.h>
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 be 1 as well because we want length of longest subarray
// which has alternate even-odd or vice-versa elements. It is not mentioned that
// they have to occur in pair.
return maxcount;
}
/* Driver code*/
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 7, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
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
longest = Math.max(longest, cnt);
if (longest == 1)
return 0;
return 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
Python
# 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
<script>
// JavaScript program to find the Length of the
// longest alternating even odd subarray
// Function to find the longest subarray
function longestEvenOddSubarray(a, n)
{
// Length of longest
// alternating subarray
let longest = 1;
let cnt = 1;
// Iterate in the array
for (let 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*/
let a = [ 1, 2, 3, 4, 5, 7, 8 ];
let n = a.length;
document.write(longestEvenOddSubarray(a, n));
// This code is contributed by Surbhi Tyagi.
</script>
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:
- Initialize a variable maxLength to 0, to keep the track of maximum length of the alternating subarray obtained.
- Initialize a variable currLen to 1 considering first element as the part of alternating subarray.
- Starting with element at index 1, compare every element with it's previous. If there nature are different, increment the currLen variable.
- Otherwise, reset the currLen to 1 again so that, this current element is considered in new alternating subarray.
- Keep storing the max length of subarray in maxLength before resetting the currLen.
- 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 <iostream>
using namespace std;
int maxEvenOdd(int arr[], int n)
{
if (n == 0)
return 0;
int maxLength = 0;
int currLen = 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 != arr[i-1] % 2)
currLen++;
else
{
// store max in maxLength
maxLength = max(maxLength, currLen);
// reset value when pattern is broken
currLen = 1;
}
}
// since, even-odd should occur in pair
if(maxLength == 1)
return 0;
// if the pair is in last
if(currLen > 1){
maxLength = max(maxLength , currLen);
}
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 and improved by Aniket Raj
Java
// Java code to find longest subarray
// of alternating even and odds
import java.util.*;
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[0] % 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(String[] args)
{
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;
System.out.print(
"Length of longest subarray of even and odds is : ");
System.out.print(maxEvenOdd(arr, n));
}
}
// This code is contributed by phasing17
Python
# Python3 code to find longest subarray of alternating even and
# odds
def maxEvenOdd(arr, n):
if (n == 0):
return 0;
maxLength = 0;
# storing the nature of first element, if
# remainder = 1, it is odd
prevOdd = arr[0] % 2;
curLength = 1;
for i in range(1, n):
# everytime we check if previous
# element has opposite even/odd
# nature or not
if (arr[i] % 2 != prevOdd):
curLength+=1;
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
arr = [ 1, 2, 3, 4, 5, 3, 7, 2, 9, 4 ];
# longest subarray should be 1 2 3 4 5 , therefore
# length = 5
n = len(arr);
print("Length of longest subarray of even and odds is :", maxEvenOdd(arr, n));
# This code is contributed by phasing17
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[0] % 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[0] % 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
OutputLength 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem