Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement
1.2.
Sample Examples
2.
Naive Approach
2.1.
Algorithm
2.2.
Implementation in C++
2.2.1.
Time Complexity
2.2.2.
Space Complexity
3.
Optimal Approach
3.1.
Algorithm
3.2.
Implementation in C++
3.2.1.
Time Complexity
3.2.2.
Space Complexity
4.
Frequently Asked Questions
4.1.
What is Subarray?
4.2.
Can Subarray be empty?
4.3.
How do you find the number of Subarrays?
5.
Conclusion
Last Updated: Mar 27, 2024

Subarrays with same Even and Odd elements

Author Harsh
0 upvote

Introduction

One of the most common data structures is the array. An array is a collection of data elements of the same type. There is a very high probability of getting a question related to an array in an interview. So in order to understand the concept of array deeply, we have to practice more and more questions related to the array. In this blog, we are going to discuss a coding problem in which we have to print the count of even-odd subarrays in an array.

Must Recommended Topic, Hash Function in Data Structure.

Problem Statement

Ninja has given you an array of integers of size N. Your task is to print the count of even-odd subarrays. Here, an even-odd array means an array that contains the same number of even and odd elements.

Sample Examples

Example 1

Input

Output

Total Number of even-odd Subarray: 6


Explanation

 

Example 2

Input

Output

Total Number of even-odd Subarray: 2


Explanation

Naive Approach

A simple approach would be to generate all the possible subarrays and check while generating whether the subarray is an even-odd subarray or not.

Algorithm

ALGORITHM(ARR):
    totalCount <- 0
    for i <- 0 to arr.size():
        for j <- i to arr.size():
            if subarray from i to j contains equal even and odd elements:
                totalCount <- totalCount + 1
        end
    end
return totalCount

Implementation in C++

#include <bits/stdc++.h>
using namespace std;

// function to check if the subarray has equal number
// of even and odd elements
bool checkEvenOdd(vector<int> arr, int i, int j){

    // variables to store the count of even and odd elements
    int evenCount = 0;
    int oddCount = 0;

    // looping through the subarray and increasing the even and odd count
    for(;i <= j; i++){
        if(arr[i] % 2 == 0) evenCount++;
        else oddCount++;
    }

    // The below expresion will return true if evenCount is equal to oddCount
    // else it will return false
    return evenCount == oddCount;
}


int getCount(vector<int> arr){

    // For storing the totalCount of even-odd subarrays
    int totalCount = 0;


    // generating subarrays and checking whether they contain
    // equal amount of even and odd subarray or not.
    for( int i = 0; i < arr.size(); i++){
        for( int j = i; j < arr.size(); j++){   
            // checking if the subarray contains equal number of even and odd
            // elements
            if (checkEvenOdd(arr, i, j)){
                totalCount++;
            } 
        }
    }

    return totalCount;
}


// main method
int main(){
    // getting array elements from user
    int n; cout << "Enter the size of the array: ";
    cin >> n;
    vector<int> arr(n);
    cout << "Enter array elements: ";
    for(int i = 0; i < n; i++) cin >> arr[i];


    // getting the count of even-odd subarrays
    cout << "Total Number of even-odd Subarray: " << getCount(arr) << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Input

Enter the size of the array: 6
Enter array elements: 5 4 7 2 1 9

 

Output

Total Number of even-odd Subarray: 6


Time Complexity

The time complexity of the above code is O(N^3) as we are generating all the possible subarrays. Here, N defines the size of the array.


Space Complexity

Constant space is used. So, the space complexity of the above approach is O(1).

You can also read about the Longest Consecutive Sequence.

Optimal Approach

A much smarter way would be to closely observe the problem and then write the algorithm according to the observations we have. In this problem, one thing is clear to us, that is the subarrays containing equal numbers of odd and even elements will always be of even length. So, in order to find the optimal solution, we can use the difference between the frequency of even and odd numbers. The difference is calculated by decrementing the difference variable by 1 if we found an even integer. otherwise, increment it by 1. Initially, the value of the difference will be 0.

As we can see in the above image, the value '0' is repeating that means, there exists an even and odd subarray between index 0 and 2. In this example, the even-odd subarray would be: 5, 4

Algorithm

ALGORITHM(arr):
    difference <- 0
    totalCount <- 0
    positive[arr.size() + 1]
    negative[arr.size() + 1]

    positive[0] <- 0

    for i <- 0 to arr.size():
        if arr[i] is even:
            difference <- difference - 1
        else:
            difference <- difference + 1
        
        if difference is negative:
            totalCount <- totalCount + negative[difference]
            negative[difference * -1] <- negative[difference] + 1
        else:
            totalCount <- totalCount + positive[difference]
            positive[difference] <- positive[difference] + 1
    end
    
return totalCount

Implementation in C++

#include <bits/stdc++.h>
using namespace std;

// function to the total count of even-odd subarrays
int getCount(vector<int> arr){
    
    // initialising totalCount and difference to 0
    int difference = 0;
    int totalCount = 0;

    // hash array to count the frequency of positive difference
    vector<int> positive(arr.size() + 1, 0);
    
    // hash array to count the frequency of negative difference
    vector<int> negative(arr.size() + 1, 0);

    // initial difference is 0, So the positive[0] will be 1
    positive[0] = 1;

    // iterating through whole array
    for(int i = 0; i < arr.size(); i++){

        // if the current element if even
        // decrease the difference count by 1
        // else increase it by 1
        if(arr[i] % 2 == 0){
            difference--;
        }
        else {
            difference++;
        }

        // Adding the hash value 'difference' to our totalCount 
        // since all prior instances of the same difference value 
        // will result in an even-odd subarray terminating at index i
        // Following that, we will increment the hash array for that 
        // 'difference' value at index i.
        // if the current difference is negative we'll use negative hash array
        // else we'll use positive hash array.
        if (difference < 0) {
			totalCount += negative[-difference];
			negative[-difference]++;
        }
		else {
			totalCount += positive[difference];
			positive[difference]++;
		}
    }

    // returning the totalCount
    return totalCount;
}

// main function
int main() {

     // Getting array elements from user
    int n; cout << "Enter the size of the array: ";
    cin >> n;
    vector<int> arr(n);
    cout << "Enter array elements: ";
    for(int i = 0; i < n; i++) cin >> arr[i];

    // Printing the total count of even-odd subarrays
    cout << "Total Number of even-odd Subarray: " << getCount(arr) << endl;
    
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Input

Enter the size of the array: 6
Enter array elements: 5 4 7 2 1 9


Output

Total Number of even-odd Subarray: 6


Time Complexity

The time complexity is O(N). As we are iterating through the whole array only once. Here, N means the size of the array.

 

Space Complexity

We are using two different hash arrays. So, the space complexity of the above approach is O(2N) Where N is the size of the array.

Check out this problem - Subarray With 0 Sum

Frequently Asked Questions

What is Subarray?

A subarray is a part of an array that is contiguous. For example, if the array is {1, 2, 3} then {1, 2} can be one of the many subarrays of the original array.
 

Can Subarray be empty?

Yes, A subarray can be empty. In computer science, the array containing 0 number of elements is considered as an empty array.
 

How do you find the number of Subarrays?

The total number of subarrays in an array of size N is N * (N + 1) / 2. We can use this equation to find the total number of subarrays. For example, if the size of the array is 3 then 3 * ( 3 + 1 ) / 2 = 6.

Conclusion

In this article, we have extensively discussed a coding problem in which we have to count the total number of subarrays that contains equal numbers even and odd elements. We have discussed two different approaches.
 

We hope that this blog has helped you enhance your knowledge about the above question and if you would like to learn more. Check out more of our blogs related to coding questions Length of the largest subarray with 0 sumLongest Subarray not having more than K Distinct ElementsCount of Subarrays with Equal Number of 1’s and 0’sK-th Largest Sum Contiguous Subarray,  and many more on our Website.

Recommended problems -

 

You can also check Interview Preparation Resources and Interview Experiences if you are interested in cracking the technical interviews at top Product-based companies like Amazon, Microsoft, Uber, etc.

Upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and more with our Coding Ninjas Studio Guided Path.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass