Open In App

Longest Subarray with only Even Elements

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[]. The task is to find the length of the longest subarray of arr[] such that it contains only even elements.

Examples: 

Input : arr[] = [5, 2, 4, 7]
Output : 2
Explanation: Subarray [2, 4] is the longest subarray containing only even elements.

Input : arr[] = [9, 8, 5, 4, 4, 4, 2, 4, 1]
Output : 5
Explanation: Subarray [4, 4, 4, 2, 4] is the longest subarray.

[Naive Approach] Checking each Subarray - O(n^3) time and O(1) space

The idea is to check every possible subarray in the array and find the length of the longest one containing only even elements. We iterate through all possible starting and ending positions, then check whether all elements in that range are even, keeping track of the maximum valid length found.

C++
// C++ program to find Length of the 
// longest Subarray with only Even Elements
#include <bits/stdc++.h>
using namespace std;

int maxEvenSub(vector<int> &arr) {
    int n = arr.size();
    int res = 0;
    
    // Check all possible subarrays
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            
            // Check if current subarray has only even elements
            bool allEven = true;
            for (int k = i; k <= j; k++) {
                if (arr[k] % 2 != 0) {
                    allEven = false;
                    break;
                }
            }
            
            // If all elements are even, update result
            if (allEven) {
                res = max(res, j - i + 1);
            }
        }
    }
    
    return res;
}

int main() {
    vector<int> arr = {5, 2, 4, 7};
    cout << maxEvenSub(arr);
    
    return 0;
}
Java
// Java program to find Length of the 
// longest Subarray with only Even Elements

class GfG {

    static int maxEvenSub(int[] arr) {
        int n = arr.length;
        int res = 0;

        // Check all possible subarrays
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {

                // Check if current subarray has only even elements
                boolean allEven = true;
                for (int k = i; k <= j; k++) {
                    if (arr[k] % 2 != 0) {
                        allEven = false;
                        break;
                    }
                }

                // If all elements are even, update result
                if (allEven) {
                    res = Math.max(res, j - i + 1);
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {5, 2, 4, 7};
        System.out.println(maxEvenSub(arr));
    }
}
Python
# Python program to find Length of the 
# longest Subarray with only Even Elements

def maxEvenSub(arr):
    n = len(arr)
    res = 0

    # Check all possible subarrays
    for i in range(n):
        for j in range(i, n):

            # Check if current subarray has only even elements
            allEven = True
            for k in range(i, j + 1):
                if arr[k] % 2 != 0:
                    allEven = False
                    break

            # If all elements are even, update result
            if allEven:
                res = max(res, j - i + 1)

    return res

if __name__ == "__main__":
    arr = [5, 2, 4, 7]
    print(maxEvenSub(arr))
C#
// C# program to find Length of the 
// longest Subarray with only Even Elements

using System;

class GfG {

    static int maxEvenSub(int[] arr) {
        int n = arr.Length;
        int res = 0;

        // Check all possible subarrays
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {

                // Check if current subarray has only even elements
                bool allEven = true;
                for (int k = i; k <= j; k++) {
                    if (arr[k] % 2 != 0) {
                        allEven = false;
                        break;
                    }
                }

                // If all elements are even, update result
                if (allEven) {
                    res = Math.Max(res, j - i + 1);
                }
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[] arr = {5, 2, 4, 7};
        Console.WriteLine(maxEvenSub(arr));
    }
}
JavaScript
// JavaScript program to find Length of the 
// longest Subarray with only Even Elements

function maxEvenSub(arr) {
    let n = arr.length;
    let res = 0;

    // Check all possible subarrays
    for (let i = 0; i < n; i++) {
        for (let j = i; j < n; j++) {

            // Check if current subarray has only even elements
            let allEven = true;
            for (let k = i; k <= j; k++) {
                if (arr[k] % 2 !== 0) {
                    allEven = false;
                    break;
                }
            }

            // If all elements are even, update result
            if (allEven) {
                res = Math.max(res, j - i + 1);
            }
        }
    }

    return res;
}

let arr = [5, 2, 4, 7];
console.log(maxEvenSub(arr));

Output
2

[Expected Approach] Using Sliding Window Approach - O(n) time and O(1) space

The idea is to use a sliding window approach by traversing the array just once, maintaining the current length of consecutive even elements. When we encounter an even element, we extend the current subarray; when we encounter an odd element, we reset our counter since it breaks the subarray of even elements.

Step by step approach:

  1. Initialize a variable to track the current length of consecutive even elements.
  2. Traverse the array once from left to right.
  3. If the current element is even, increment the current length and update the maximum length if needed.
  4. If the current element is odd, reset the current length to zero as it breaks the sequence.
  5. Return the maximum length found as the final answer.
C++
// C++ program to find Length of the 
// longest Subarray with only Even Elements
#include <bits/stdc++.h>
using namespace std;

int maxEvenSub(vector<int> &arr) {
    int n = arr.size();
    int res = 0;
    int curr = 0;
    
    for (int i = 0; i < n; i++) {
        
        // If current element is even, increment length
        if (arr[i] % 2 == 0) {
            curr++;
            res = max(res, curr);
        }
        
        // If current element is odd, reset length
        else {
            curr = 0;
        }
    }
    
    return res;
}

int main() {
    vector<int> arr = {5, 2, 4, 7};
    cout << maxEvenSub(arr);
    
    return 0;
}
Java
// Java program to find Length of the 
// longest Subarray with only Even Elements

class GfG {

    static int maxEvenSub(int[] arr) {
        int n = arr.length;
        int res = 0;
        int curr = 0;

        for (int i = 0; i < n; i++) {

            // If current element is even, increment length
            if (arr[i] % 2 == 0) {
                curr++;
                res = Math.max(res, curr);
            }

            // If current element is odd, reset length
            else {
                curr = 0;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {5, 2, 4, 7};
        System.out.println(maxEvenSub(arr));
    }
}
Python
# Python program to find Length of the 
# longest Subarray with only Even Elements

def maxEvenSub(arr):
    n = len(arr)
    res = 0
    curr = 0

    for i in range(n):

        # If current element is even, increment length
        if arr[i] % 2 == 0:
            curr += 1
            res = max(res, curr)

        # If current element is odd, reset length
        else:
            curr = 0

    return res

if __name__ == "__main__":
    arr = [5, 2, 4, 7]
    print(maxEvenSub(arr))
C#
// C# program to find Length of the 
// longest Subarray with only Even Elements

using System;

class GfG {

    static int maxEvenSub(int[] arr) {
        int n = arr.Length;
        int res = 0;
        int curr = 0;

        for (int i = 0; i < n; i++) {

            // If current element is even, increment length
            if (arr[i] % 2 == 0) {
                curr++;
                res = Math.Max(res, curr);
            }

            // If current element is odd, reset length
            else {
                curr = 0;
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[] arr = {5, 2, 4, 7};
        Console.WriteLine(maxEvenSub(arr));
    }
}
JavaScript
// JavaScript program to find Length of the 
// longest Subarray with only Even Elements

function maxEvenSub(arr) {
    let n = arr.length;
    let res = 0;
    let curr = 0;

    for (let i = 0; i < n; i++) {

        // If current element is even, increment length
        if (arr[i] % 2 === 0) {
            curr++;
            res = Math.max(res, curr);
        }

        // If current element is odd, reset length
        else {
            curr = 0;
        }
    }

    return res;
}

let arr = [5, 2, 4, 7];
console.log(maxEvenSub(arr));

Output
2

Similar Reads