Longest subarray with all even or all odd elements
Last Updated :
16 Nov, 2023
Given an array A[ ] of N non-negative integers, the task is to find the length of the longest sub-array such that all the elements in that sub-array are odd or even.
Examples:
Input: A[] = {2, 5, 7, 2, 4, 6, 8, 3}
Output: 4
Explanation: Sub-array {2, 4, 6, 8} of length 4 has all even elements
Input: A[] = {2, 3, 2, 5, 7, 3}
Output: 3
Explanation: Sub-array {5, 7, 3} of length 3 has all odd elements
Naive Approach: A naive approach to solve this problem is to consider all the contiguous sub-arrays and for each sub-array, check if all the elements are even or odd. The longest of them will be the answer.
Steps to implement:
- Declare a variable “ans” with value 0 because if no such subarray exists then 0 will be the answer
- Run two nested loops to find all subarrays
- Find the length of each subarray
- Make a boolean variable for each subarray that will initially contain false and when that subarray has all elements even or all elements odd then make that boolean variable true.
- If the boolean variable is true for any subarray, it is the required subarray. So update ans as the maximum of ans and the length of that subarray.
Code-
C++
#include <bits/stdc++.h>
using namespace std;
int LongestOddEvenSubarray( int arr[], int N)
{
int ans=0;
for ( int i=0;i<N;i++){
int length=0;
for ( int j=i;j<N;j++){
length++;
bool val= false ;
int k=i;
while (k<=j){
if (arr[k]%2!=0){ break ;}
k++;
}
if (k==j+1){val= true ;}
k=i;
while (k<=j){
if (arr[k]%2!=1){ break ;}
k++;
}
if (k==j+1){val= true ;}
if (val== true ){
ans=max(ans,length);
}
}
}
return ans;
}
int main()
{
int arr[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << LongestOddEvenSubarray(arr, N);
return 0;
}
|
Java
import java.util.*;
class Main {
static int longestOddEvenSubarray( int [] arr, int N) {
int ans = 0 ;
for ( int i = 0 ; i < N; i++) {
int length = 0 ;
for ( int j = i; j < N; j++) {
length++;
boolean val = false ;
int k = i;
while (k <= j) {
if (arr[k] % 2 != 0 ) {
break ;
}
k++;
}
if (k == j + 1 ) {
val = true ;
}
k = i;
while (k <= j) {
if (arr[k] % 2 != 1 ) {
break ;
}
k++;
}
if (k == j + 1 ) {
val = true ;
}
if (val) {
ans = Math.max(ans, length);
}
}
}
return ans;
}
public static void main(String[] args) {
int [] arr = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 };
int N = arr.length;
System.out.println(longestOddEvenSubarray(arr, N));
}
}
|
Python3
def longest_odd_even_subarray(arr, N):
ans = 0
for i in range (N):
length = 0
for j in range (i, N):
length + = 1
val = False
k = i
while k < = j:
if arr[k] % 2 ! = 0 :
break
k + = 1
if k = = j + 1 :
val = True
k = i
while k < = j:
if arr[k] % 2 ! = 1 :
break
k + = 1
if k = = j + 1 :
val = True
if val:
ans = max (ans, length)
return ans
if __name__ = = "__main__" :
arr = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ]
N = len (arr)
print (longest_odd_even_subarray(arr, N))
|
C#
using System;
class GFG
{
static int LongestOddEvenSubarray( int [] arr, int N)
{
int ans = 0;
for ( int i = 0; i < N; i++)
{
int length = 0;
for ( int j = i; j < N; j++)
{
length++;
bool val = false ;
int k = i;
while (k <= j)
{
if (arr[k] % 2 != 0)
{
break ;
}
k++;
}
if (k == j + 1)
{
val = true ;
}
k = i;
while (k <= j)
{
if (arr[k] % 2 != 1)
{
break ;
}
k++;
}
if (k == j + 1)
{
val = true ;
}
if (val == true )
{
ans = Math.Max(ans, length);
}
}
}
return ans;
}
static void Main()
{
int [] arr = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = arr.Length;
Console.WriteLine(LongestOddEvenSubarray(arr, N));
}
}
|
Javascript
function longestOddEvenSubarray(arr) {
let ans = 0;
for (let i = 0; i < arr.length; i++) {
let length = 0;
for (let j = i; j < arr.length; j++) {
length++;
let val = false ;
let k = i;
while (k <= j) {
if (arr[k] % 2 !== 0) {
break ;
}
k++;
}
if (k === j + 1) {
val = true ;
}
k = i;
while (k <= j) {
if (arr[k] % 2 !== 1) {
break ;
}
k++;
}
if (k === j + 1) {
val = true ;
}
if (val) {
ans = Math.max(ans, length);
}
}
}
return ans;
}
const arr = [2, 5, 7, 2, 4, 6, 8, 3];
console.log(longestOddEvenSubarray(arr));
|
Time Complexity: O(N3), because of two nested loops to find all subarray and the third loop is for finding that subarray contains all elements odd or all elements even
Auxiliary Space: O(1), because no extra space has been used
Efficient Approach: The main idea to solve this problem is to use Dynamic Programming(it has both the properties – Optimal Substructure and Overlapping Subproblems) such that if there are some contiguous odd elements, then the very next odd element will increase the length of that contiguous array by one. And this is also true for even elements. Follow the steps below to solve the problem:
- Initialize an array dp[ ] where dp[i] stores the length of sub-array that ends at A[i].
- Initialize dp[0] with 1.
- Initialize the variable ans as 1 to store the answer.
- Iterate over the range [1, N] using the variable i and perform the following steps:
- If A[i]%2 is equal to A[i-1]%2, then set the value of dp[i] as dp[i-1]+1.
- Else, set the value of dp[i] as 1.
- Iterate over the range [0, N] using the variable i and perform the following steps:
- Set the value of ans as the maximum of ans or dp[i].
- After performing the above steps, print the value of ans as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LongestOddEvenSubarray( int A[], int N)
{
int dp[N];
dp[0] = 1;
int ans = 1;
for ( int i = 1; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
|| (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
dp[i] = dp[i - 1] + 1;
}
else
dp[i] = 1;
}
for ( int i = 0; i < N; i++)
ans = max(ans, dp[i]);
return ans;
}
int main()
{
int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = sizeof (A) / sizeof (A[0]);
cout << LongestOddEvenSubarray(A, N);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int LongestOddEvenSubarray( int A[], int N)
{
int dp[] = new int [N];
dp[ 0 ] = 1 ;
int ans = 1 ;
for ( int i = 1 ; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1 ] % 2 == 0 )
|| (A[i] % 2 != 0 && A[i - 1 ] % 2 != 0 )) {
dp[i] = dp[i - 1 ] + 1 ;
}
else
dp[i] = 1 ;
}
for ( int i = 0 ; i < N; i++)
ans = Math.max(ans, dp[i]);
return ans;
}
public static void main(String[] args)
{
int A[] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 };
int N = A.length;
System.out.println(LongestOddEvenSubarray(A, N));
}
}
|
Python3
def LongestOddEvenSubarray(A, N):
dp = [ 0 for i in range (N)]
dp[ 0 ] = 1
ans = 1
for i in range ( 1 , N, 1 ):
if ((A[i] % 2 = = 0 and A[i - 1 ] % 2 = = 0 ) or (A[i] % 2 ! = 0 and A[i - 1 ] % 2 ! = 0 )):
dp[i] = dp[i - 1 ] + 1
else :
dp[i] = 1
for i in range (N):
ans = max (ans, dp[i])
return ans
if __name__ = = '__main__' :
A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ]
N = len (A)
print (LongestOddEvenSubarray(A, N))
|
C#
using System;
class GFG{
static int LongestOddEvenSubarray( int [] A, int N)
{
int [] dp = new int [N];
dp[0] = 1;
int ans = 1;
for ( int i = 1; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
|| (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
dp[i] = dp[i - 1] + 1;
}
else
dp[i] = 1;
}
for ( int i = 0; i < N; i++)
ans = Math.Max(ans, dp[i]);
return ans;
}
public static void Main()
{
int [] A = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = A.Length;
Console.Write(LongestOddEvenSubarray(A, N));
}
}
|
Javascript
<script>
function LongestOddEvenSubarray(A, N)
{
let dp = new Array(N);
dp[0] = 1;
let ans = 1;
for (let i = 1; i < N; i++)
{
if (
(A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||
(A[i] % 2 != 0 && A[i - 1] % 2 != 0)
) {
dp[i] = dp[i - 1] + 1;
} else dp[i] = 1;
}
for (let i = 0; i < N; i++)
ans = Math.max(ans, dp[i]);
return ans;
}
let A = [2, 5, 7, 2, 4, 6, 8, 3];
let N = A.length;
document.write(LongestOddEvenSubarray(A, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Space Optimization: It is possible to further optimize the space complexity of the above approach by observing that, for calculating dp[i], only the value of dp[i-1] is relevant. So, store dp[i-1] in a variable and update the variable in each iteration. Also, update the answer in each iteration. Follow the steps below to solve the problem:
- Initialize the variables dp as 1 to store the length of the sub-array till i-1 and ans as 1 to store the answer.
- Iterate over the range [1, N] using the variable i and perform the following steps:
- If A[i]%2 is equal to A[i-1]%2, then set the value of dp as dp+1 and set the value of ans as the maximum of ans or dp.
- Else, set the value of dp as 1.
- After performing the above steps, print the value of ans as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LongestOddEvenSubarray( int A[], int N)
{
int dp;
dp = 1;
int ans = 1;
for ( int i = 1; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
|| (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
dp = dp + 1;
ans = max(ans, dp);
}
else
dp = 1;
}
return ans;
}
int main()
{
int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = sizeof (A) / sizeof (A[0]);
cout << LongestOddEvenSubarray(A, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int LongestOddEvenSubarray( int A[], int N)
{
int dp;
dp = 1 ;
int ans = 1 ;
for ( int i = 1 ; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1 ] % 2 == 0 )
|| (A[i] % 2 != 0 && A[i - 1 ] % 2 != 0 )) {
dp = dp + 1 ;
ans = Math.max(ans, dp);
}
else
dp = 1 ;
}
return ans;
}
public static void main(String[] args)
{
int A[] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 };
int N = A.length;
System.out.print(LongestOddEvenSubarray(A, N));
}
}
|
Python3
def LongestOddEvenSubarray(A, N):
dp = 1
ans = 1
for i in range ( 1 , N):
if ((A[i] % 2 = = 0 and A[i - 1 ] % 2 = = 0 ) or (A[i] % 2 ! = 0 and A[i - 1 ] % 2 ! = 0 )):
dp = dp + 1
ans = max (ans, dp)
else :
dp = 1
return ans
A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ]
N = len (A)
print (LongestOddEvenSubarray(A, N))
|
C#
using System;
public class GFG
{
static int longestOddEvenSubarray( int []A, int N)
{
int dp;
dp = 1;
int ans = 1;
for ( int i = 1; i < N; i++) {
if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
|| (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
dp = dp + 1;
ans = Math.Max(ans, dp);
}
else
dp = 1;
}
return ans;
}
public static void Main(String[] args)
{
int []A = { 2, 5, 7, 2, 4, 6, 8, 3 };
int N = A.Length;
Console.Write(longestOddEvenSubarray(A, N));
}
}
|
Javascript
<script>
function LongestOddEvenSubarray(A, N) {
let dp;
dp = 1;
let ans = 1;
for (let i = 1; i < N; i++) {
if (
(A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||
(A[i] % 2 != 0 && A[i - 1] % 2 != 0)
) {
dp = dp + 1;
ans = Math.max(ans, dp);
} else dp = 1;
}
return ans;
}
let A = [2, 5, 7, 2, 4, 6, 8, 3];
let N = A.length;
document.write(LongestOddEvenSubarray(A, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...