Length of longest Subarray with equal number of odd and even elements

Given an integer array arr[], the task is to find the length of the longest subarray with an equal number of odd and even elements.
Examples:
Input: arr[] = {1, 2, 1, 2}
Output: 4Â
Explanation:Â
Subarrays in the given array are –Â
{{1}, {1, 2}, {1, 2, 1}, {1, 2, 1, 2}, {2}, {2, 1}, {2, 1, 2}, {1}, {1, 2}, {2}}Â
where the length of the longest subarray with an equal number of even and odd elements is 4 – {1, 2, 1, 2}Input: arr[] = {12, 4, 7, 8, 9, 2, 11, 0, 2, 13}Â
Output: 8Â Â
Naive Approach: Simple solution is to consider all subarrays one by one and check the count of even and odd elements in the subarray. Then find the maximum length of those subarray that contain an equal number of even elements and odd elements.Â
Steps to implement-
- Initialize a variable ans to store the final answer
- Run two loops to find all subarrays and simultaneously find their length
- After that count number of odd elements and the number of even elements in that
- If that subarray contains an equal number of odd and even elements thenÂ
- Update ans with maximum of ans and the length of that subarray
Code-
C++
// C++ program to find the length// of the longest sub-array with an// equal number of odd and even elements#include <bits/stdc++.h>using namespace std;Â
// Function that returns the length of// the longest sub-array with an equal// number of odd and even elementsint maxSubarrayLength(int arr[], int N){    //To store answer    int ans=0;         //Find all subarray    for(int i=0;i<N;i++){        //To store length of subarray        int length=0;        for(int j=i;j<N;j++){            //Increment the length            length++;                         //To store count of even elements            int even=0;                         //To store count of odd elements            int odd=0;                         //Find the number of even elements and odd elements            for(int k=i;k<=j;k++){                if(arr[k]%2==0){even++;}                else if(arr[k]%2==1){odd++;}            }                        //When subarray contains equal number of odd            //and even elements            if(odd==even){                ans=max(ans,length);            }                     }    }    return ans;}Â
// Driver Codeint main(){    int arr[] = { 12, 4, 7, 8, 9, 2,                        11, 0, 2, 13 };    int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << maxSubarrayLength(arr, n);Â
    return 0;} |
Java
import java.util.*;Â
public class Main {Â
    // Function that returns the length of    // the longest sub-array with an equal    // number of odd and even elements    static int maxSubarrayLength(int[] arr, int N)    {        // To store answer        int ans = 0;Â
        // Find all subarrays        for (int i = 0; i < N; i++) {            // To store length of subarray            int length = 0;            for (int j = i; j < N; j++) {                // Increment the length                length++;Â
                // To store count of even elements                int even = 0;Â
                // To store count of odd elements                int odd = 0;Â
                // Find the number of even elements and odd                // elements                for (int k = i; k <= j; k++) {                    if (arr[k] % 2 == 0) {                        even++;                    }                    else if (arr[k] % 2 == 1) {                        odd++;                    }                }Â
                // When subarray contains equal number of                // odd and even elements                if (odd == even) {                    ans = Math.max(ans, length);                }            }        }        return ans;    }Â
    // Driver Code    public static void main(String[] args)    {        int[] arr = { 12, 4, 7, 8, 9, 2, 11, 0, 2, 13 };        int n = arr.length;Â
        System.out.println(maxSubarrayLength(arr, n));    }} |
Python
# Function that returns the length of# the longest sub-array with an equal# number of odd and even elementsÂ
Â
def maxSubarrayLength(arr, N):    # To store the answer    ans = 0Â
    # Find all subarrays    for i in range(N):        # To store the length of subarray        length = 0        for j in range(i, N):            # Increment the length            length += 1Â
            # To store the count of even elements            even = 0Â
            # To store the count of odd elements            odd = 0Â
            # Find the number of even elements and odd elements            for k in range(i, j + 1):                if arr[k] % 2 == 0:                    even += 1                elif arr[k] % 2 == 1:                    odd += 1Â
            # When the subarray contains an equal number of odd            # and even elements            if odd == even:                ans = max(ans, length)Â
    return ansÂ
Â
# Driver Codeif __name__ == "__main__":Â Â Â Â arr = [12, 4, 7, 8, 9, 2, 11, 0, 2, 13]Â Â Â Â n = len(arr)Â
    print(maxSubarrayLength(arr, n))Â
# This code is contributed by Taranpreet Singh. |
C#
using System;Â
class GFG{    // Function that returns the length of    // the longest sub-array with an equal    // number of odd and even elements    static int MaxSubarrayLength(int[] arr, int N)    {        // To store the answer        int ans = 0;        // Find all subarrays        for (int i = 0; i < N; i++)        {            // To store the length of the subarray            int length = 0;            for (int j = i; j < N; j++)            {                // Increment the length                length++;                // To store count of even elements                int even = 0;                // To store count of odd elements                int odd = 0;                // Find the number of even elements and odd elements                for (int k = i; k <= j; k++)                {                    if (arr[k] % 2 == 0)                    {                        even++;                    }                    else if (arr[k] % 2 == 1)                    {                        odd++;                    }                }                // When subarray contains an equal number of odd                // and even elements                if (odd == even)                {                    ans = Math.Max(ans, length);                }            }        }        return ans;    }    // Driver Code    static void Main()    {        int[] arr = { 12, 4, 7, 8, 9, 2, 11, 0, 2, 13 };        int n = arr.Length;        Console.WriteLine(MaxSubarrayLength(arr, n));    }} |
Javascript
// JavaScript program to find the length// of the longest sub-array with an// equal number of odd and even elements  // Function that returns the length of// the longest sub-array with an equal// number of odd and even elements function maxSubarrayLength(arr, N) {    //To store answer    let ans=0;          //Find all subarray    for(let i=0;i<N;i++){        //To store length of subarray        let length=0;        for(let j=i;j<N;j++){            //Increment the length            length++;                          //To store count of even elements            let even=0;                          //To store count of odd elements            let odd=0;                          //Find the number of even elements and odd elements            for(let k=i;k<=j;k++){                if(arr[k]%2==0){even++;}                else if(arr[k]%2==1){odd++;}            }                         //When subarray contains equal number of odd            //and even elements            if(odd==even){                ans=Math.max(ans,length);            }                      }    }    return ans; }Â
// Driver Codevar arr = [12, 4, 7, 8, 9, 2,                    11, 0, 2, 13 ];var n = arr.length;console.log(maxSubarrayLength(arr, n)); |
8
Time Complexity: O(N3), because of two nested loops to find all subarrays and a third loop to find the number of odd and even elements in a subarray
Auxiliary Space: O(1), because no extra space has been used
Â
Efficient Approach: The idea is to consider the odd elements as 1 and even elements as -1 and return the length of the longest sub-array with the sum equal to 0. The subarray with a given sum can be found using this method.Â
Time Complexity: O(N)Â
Below is the implementation of the above approach:Â
C++
// C++ program to find the length// of the longest sub-array with an// equal number of odd and even elements#include <bits/stdc++.h>using namespace std;Â
// Function that returns the length of// the longest sub-array with an equal// number of odd and even elementsint maxSubarrayLength(int* A, int N){    // Initialize variable to store result    int maxLen = 0;Â
    // Initialize variable to store sum    int curr_sum = 0;Â
    // Create an empty map to store    // index of the sum    unordered_map<int, int> hash;Â
    // Loop through the array    for (int i = 0; i < N; i++) {        if (A[i] % 2 == 0)            curr_sum -= 1;        else            curr_sum += 1;Â
        // Check if number of even and        // odd elements are equal        if (curr_sum == 0)            maxLen = max(maxLen, i + 1);Â
        // If curr_sum already exists in map        // we have a subarray with 0 sum, i.e,        // equal number of odd and even number        if (hash.find(curr_sum) != hash.end())            maxLen = max(maxLen,                        i - hash[curr_sum]);Â
        // Store the index of the sum        else            hash[curr_sum] = i;    }    return maxLen;}Â
// Driver Codeint main(){    int arr[] = { 12, 4, 7, 8, 9, 2,                        11, 0, 2, 13 };    int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << maxSubarrayLength(arr, n);Â
    return 0;} |
Java
// Java program to find the length// of the longest sub-array with an// equal number of odd and even elementsimport java.util.*;Â
class GFG{Â
// Function that returns the length of// the longest sub-array with an equal// number of odd and even elementsstatic int maxSubarrayLength(int []A, int N){    // Initialize variable to store result    int maxLen = 0;Â
    // Initialize variable to store sum    int curr_sum = 0;Â
    // Create an empty map to store    // index of the sum    HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();Â
    // Loop through the array    for (int i = 0; i < N; i++)    {        if (A[i] % 2 == 0)            curr_sum -= 1;        else            curr_sum += 1;Â
        // Check if number of even and        // odd elements are equal        if (curr_sum == 0)            maxLen = Math.max(maxLen, i + 1);Â
        // If curr_sum already exists in map        // we have a subarray with 0 sum, i.e,        // equal number of odd and even number        if (hash.containsKey(curr_sum))            maxLen = Math.max(maxLen,                        i - hash.get(curr_sum));Â
        // Store the index of the sum        else {            hash.put(curr_sum, i);        }    }    return maxLen;}Â
// Driver Codepublic static void main(String[] args){    int arr[] = { 12, 4, 7, 8, 9, 2,                        11, 0, 2, 13 };    int n = arr.length;Â
    System.out.print(maxSubarrayLength(arr, n));}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program to find the length # of the longest sub-array with an # equal number of odd and even elements Â
# Function that returns the length of # the longest sub-array with an equal # number of odd and even elements def maxSubarrayLength(A, N) : Â
    # Initialize variable to store result     maxLen = 0; Â
    # Initialize variable to store sum     curr_sum = 0; Â
    # Create an empty map to store     # index of the sum     hash = {}; Â
    # Loop through the array     for i in range(N) :        if (A[i] % 2 == 0) :            curr_sum -= 1;         else :            curr_sum += 1; Â
        # Check if number of even and         # odd elements are equal         if (curr_sum == 0) :            maxLen = max(maxLen, i + 1); Â
        # If curr_sum already exists in map         # we have a subarray with 0 sum, i.e,         # equal number of odd and even number         if curr_sum in hash :            maxLen = max(maxLen, i - hash[curr_sum]); Â
        # Store the index of the sum         else :            hash[curr_sum] = i;          return maxLen; Â
# Driver Code if __name__ == "__main__" : Â
    arr = [ 12, 4, 7, 8, 9, 2, 11, 0, 2, 13 ];     n = len(arr); Â
    print(maxSubarrayLength(arr, n)); Â
# This code is contributed by AnkitRai01 |
C#
// C# program to find the length// of the longest sub-array with an// equal number of odd and even elementsusing System;using System.Collections.Generic;Â
class GFG{Â
// Function that returns the length of// the longest sub-array with an equal// number of odd and even elementsstatic int maxSubarrayLength(int []A, int N){    // Initialize variable to store result    int maxLen = 0;Â
    // Initialize variable to store sum    int curr_sum = 0;Â
    // Create an empty map to store    // index of the sum    Dictionary<int, int> hash = new Dictionary<int, int>();Â
    // Loop through the array    for (int i = 0; i < N; i++)    {        if (A[i] % 2 == 0)            curr_sum -= 1;        else            curr_sum += 1;Â
        // Check if number of even and        // odd elements are equal        if (curr_sum == 0)            maxLen = Math.Max(maxLen, i + 1);Â
        // If curr_sum already exists in map        // we have a subarray with 0 sum, i.e,        // equal number of odd and even number        if (hash.ContainsKey(curr_sum))            maxLen = Math.Max(maxLen,                        i - hash[curr_sum]);Â
        // Store the index of the sum        else {            hash.Add(curr_sum, i);        }    }    return maxLen;}Â
// Driver Codepublic static void Main(String[] args){    int []arr = { 12, 4, 7, 8, 9, 2,                        11, 0, 2, 13 };    int n = arr.Length;    Console.Write(maxSubarrayLength(arr, n));}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program to find the length// of the longest sub-array with an// equal number of odd and even elementsÂ
// Function that returns the length of// the longest sub-array with an equal// number of odd and even elementsfunction maxSubarrayLength(A, N){    // Initialize variable to store result    var maxLen = 0;Â
    // Initialize variable to store sum    var curr_sum = 0;Â
    // Create an empty map to store    // index of the sum    var hash = new Map();Â
    // Loop through the array    for (var i = 0; i < N; i++) {        if (A[i] % 2 == 0)            curr_sum -= 1;        else            curr_sum += 1;Â
        // Check if number of even and        // odd elements are equal        if (curr_sum == 0)            maxLen = Math.max(maxLen, i + 1);Â
        // If curr_sum already exists in map        // we have a subarray with 0 sum, i.e,        // equal number of odd and even number        if (hash.has(curr_sum))            maxLen = Math.max(maxLen,                        i - hash.get(curr_sum));Â
        // Store the index of the sum        else            hash.set(curr_sum, i);    }    return maxLen;}Â
// Driver Codevar arr = [12, 4, 7, 8, 9, 2,                    11, 0, 2, 13 ];var n = arr.length;document.write( maxSubarrayLength(arr, n));Â
</script> |
8
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the size of the given array.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



