Skip to content
Related Articles

Related Articles

Improve Article

Longest subarray with all even or all odd elements

  • Difficulty Level : Medium
  • Last Updated : 13 Aug, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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.
Time Complexity: O(N^2)
Auxiliary Space: O(1)

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++




// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate longest substring
// with odd or even elements
int LongestOddEvenSubarray(int A[], int N)
{
    // Initializing dp[]
    int dp[N];
 
    // Initializing dp[0] with 1
    dp[0] = 1;
 
    // ans will store the final answer
    int ans = 1;
 
    // Traversing the array from index 1 to N - 1
    for (int i = 1; i < N; i++) {
 
        // Checking both current and previous element
        // is even or odd
        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
            // Updating dp[i] with dp[i-1] + 1
            dp[i] = dp[i - 1] + 1;
        }
        else
            dp[i] = 1;
    }
 
    for (int i = 0; i < N; i++)
        // Storing max element to ans
        ans = max(ans, dp[i]);
 
    // Returning the final answer
    return ans;
}
 
// Driver Code
int main()
{
    // Input
    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    cout << LongestOddEvenSubarray(A, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to calculate longest substring
    // with odd or even elements
    static int LongestOddEvenSubarray(int A[], int N)
    {
       
        // Initializing dp[]
        int dp[] = new int[N];
 
        // Initializing dp[0] with 1
        dp[0] = 1;
 
        // ans will store the final answer
        int ans = 1;
 
        // Traversing the array from index 1 to N - 1
        for (int i = 1; i < N; i++) {
 
            // Checking both current and previous element
            // is even or odd
            if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
                || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
                // Updating dp[i] with dp[i-1] + 1
                dp[i] = dp[i - 1] + 1;
            }
            else
                dp[i] = 1;
        }
 
        for (int i = 0; i < N; i++)
            // Storing max element to ans
            ans = Math.max(ans, dp[i]);
 
        // Returning the final answer
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input
        int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
        int N = A.length;
 
        // Function call
        System.out.println(LongestOddEvenSubarray(A, N));
    }
}
 
// This code is contributed by Potta Lokesh

C#




// C# program for the above approach
using System;
 
class GFG{
 
    // Function to calculate longest substring
    // with odd or even elements
    static int LongestOddEvenSubarray(int[] A, int N)
    {
       
        // Initializing dp[]
        int[] dp = new int[N];
 
        // Initializing dp[0] with 1
        dp[0] = 1;
 
        // ans will store the final answer
        int ans = 1;
 
        // Traversing the array from index 1 to N - 1
        for (int i = 1; i < N; i++) {
 
            // Checking both current and previous element
            // is even or odd
            if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
                || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
                // Updating dp[i] with dp[i-1] + 1
                dp[i] = dp[i - 1] + 1;
            }
            else
                dp[i] = 1;
        }
 
        for (int i = 0; i < N; i++)
           
            // Storing max element to ans
            ans = Math.Max(ans, dp[i]);
 
        // Returning the final answer
        return ans;
    }
 
// Driver Code
public static void Main()
{
    // Input
        int[] A = { 2, 5, 7, 2, 4, 6, 8, 3 };
        int N = A.Length;
 
        // Function call
        Console.Write(LongestOddEvenSubarray(A, N));
}
}
 
// This code is contributed by target_2.

Python3




# Python 3 implementation for the above approach
 
# Function to calculate longest substring
# with odd or even elements
def LongestOddEvenSubarray(A, N):
    # Initializing dp[]
    dp = [0 for i in range(N)]
 
    # Initializing dp[0] with 1
    dp[0] = 1
 
    # ans will store the final answer
    ans = 1
 
    # Traversing the array from index 1 to N - 1
    for i in range(1, N, 1):
       
        # Checking both current and previous element
        # is even or odd
        if ((A[i] % 2 == 0 and A[i - 1] % 2 == 0) or (A[i] % 2 != 0 and A[i - 1] % 2 != 0)):
             
            # Updating dp[i] with dp[i-1] + 1
            dp[i] = dp[i - 1] + 1
        else:
            dp[i] = 1
 
    for i in range(N):
        # Storing max element to ans
        ans = max(ans, dp[i])
 
    # Returning the final answer
    return ans
 
# Driver Code
if __name__ == '__main__':
    # Input
    A = [2, 5, 7, 2, 4, 6, 8, 3]
    N = len(A)
 
    # Function call
    print(LongestOddEvenSubarray(A, N))
     
    # This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
 
// JavaScript implementation for the above approach
 
// Function to calculate longest substring
// with odd or even elements
function LongestOddEvenSubarray(A, N)
{
 
  // Initializing dp[]
  let dp = new Array(N);
 
  // Initializing dp[0] with 1
  dp[0] = 1;
 
  // ans will store the final answer
  let ans = 1;
 
  // Traversing the array from index 1 to N - 1
  for (let i = 1; i < N; i++)
  {
   
    // Checking both current and previous element
    // is even or odd
    if (
      (A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||
      (A[i] % 2 != 0 && A[i - 1] % 2 != 0)
    ) {
      // Updating dp[i] with dp[i-1] + 1
      dp[i] = dp[i - 1] + 1;
    } else dp[i] = 1;
  }
 
  for (let i = 0; i < N; i++)
   
    // Storing max element to ans
    ans = Math.max(ans, dp[i]);
 
  // Returning the final answer
  return ans;
}
 
// Driver Code
// Input
let A = [2, 5, 7, 2, 4, 6, 8, 3];
let N = A.length;
 
// Function call
document.write(LongestOddEvenSubarray(A, N));
 
// This code is contributed by _saurabh_jaiswal.
</script>
Output
4

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++




// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate longest substring
// with odd or even elements
int LongestOddEvenSubarray(int A[], int N)
{
    // Initializing dp
    int dp;
 
    // Initializing dp with 1
    dp = 1;
 
    // ans will store the final answer
    int ans = 1;
 
    // Traversing the array from index 1 to N - 1
    for (int i = 1; i < N; i++) {
 
        // Checking both current and previous element
        // is even or odd
        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
            // Updating dp with (previous dp value) + 1
            dp = dp + 1;
 
            // Storing max element so far to ans
            ans = max(ans, dp);
        }
        else
            dp = 1;
    }
 
    // Returning the final answer
    return ans;
}
 
// Driver code
int main()
{
    // Input
    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function call
    cout << LongestOddEvenSubarray(A, N);
 
    return 0;
}

Java




// Java implementation for the above approach
import java.util.*;
class GFG
{
 
// Function to calculate longest subString
// with odd or even elements
static int LongestOddEvenSubarray(int A[], int N)
{
   
    // Initializing dp
    int dp;
 
    // Initializing dp with 1
    dp = 1;
 
    // ans will store the final answer
    int ans = 1;
 
    // Traversing the array from index 1 to N - 1
    for (int i = 1; i < N; i++) {
 
        // Checking both current and previous element
        // is even or odd
        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
            // Updating dp with (previous dp value) + 1
            dp = dp + 1;
 
            // Storing max element so far to ans
            ans = Math.max(ans, dp);
        }
        else
            dp = 1;
    }
 
    // Returning the final answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
   
    // Input
    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };
    int N = A.length;
 
    // Function call
    System.out.print(LongestOddEvenSubarray(A, N));
}
}
 
// This code is contributed by Amit Katiyar

Python3




# Python implementation for the above approach
 
# Function to calculate longest substring
# with odd or even elements
def LongestOddEvenSubarray(A, N):
     
    # Initializing dp
    # Initializing dp with 1
    dp = 1
     
    # ans will store the final answer
    ans = 1
     
    # Traversing the array from index 1 to N - 1
    for i in range(1, N):
       
        # Checking both current and previous element
        # is even or odd
        if ((A[i] % 2 == 0 and A[i - 1] % 2 == 0) or (A[i] % 2 != 0 and A[i - 1] % 2 != 0)):
             
            # Updating dp with (previous dp value) + 1
            dp = dp + 1
             
            # Storing max element so far to ans
            ans = max(ans, dp)
        else:
            dp = 1
             
    # Returning the final answer
    return ans
 
# Driver code
 
# Input
A =  [2, 5, 7, 2, 4, 6, 8, 3 ]
N = len(A)
 
# Function call
print(LongestOddEvenSubarray(A, N))
 
# This code is contributed by shivani

C#




// C# implementation for the above approach
using System;
 
public class GFG
{
 
// Function to calculate longest subString
// with odd or even elements
static int longestOddEvenSubarray(int []A, int N)
{
   
    // Initializing dp
    int dp;
 
    // Initializing dp with 1
    dp = 1;
 
    // ans will store the readonly answer
    int ans = 1;
 
    // Traversing the array from index 1 to N - 1
    for (int i = 1; i < N; i++) {
 
        // Checking both current and previous element
        // is even or odd
        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)
            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {
 
            // Updating dp with (previous dp value) + 1
            dp = dp + 1;
 
            // Storing max element so far to ans
            ans = Math.Max(ans, dp);
        }
        else
            dp = 1;
    }
 
    // Returning the readonly answer
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
   
    // Input
    int []A = { 2, 5, 7, 2, 4, 6, 8, 3 };
    int N = A.Length;
 
    // Function call
    Console.Write(longestOddEvenSubarray(A, N));
}
}
 
// This code is contributed by shikhasingrajput

Javascript




<script>
// Javascript implementation for the above approach
 
// Function to calculate longest substring
// with odd or even elements
function LongestOddEvenSubarray(A, N) {
  // Initializing dp
  let dp;
 
  // Initializing dp with 1
  dp = 1;
 
  // ans will store the final answer
  let ans = 1;
 
  // Traversing the array from index 1 to N - 1
  for (let i = 1; i < N; i++) {
    // Checking both current and previous element
    // is even or odd
    if (
      (A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||
      (A[i] % 2 != 0 && A[i - 1] % 2 != 0)
    ) {
      // Updating dp with (previous dp value) + 1
      dp = dp + 1;
 
      // Storing max element so far to ans
      ans = Math.max(ans, dp);
    } else dp = 1;
  }
 
  // Returning the final answer
  return ans;
}
 
// Driver code
// Input
let A = [2, 5, 7, 2, 4, 6, 8, 3];
let N = A.length;
 
// Function call
document.write(LongestOddEvenSubarray(A, N));
 
</script>
Output
4

Time Complexity: O(N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :