Open In App

Check if even and odd count of elements can be made equal in Array

Last Updated : 05 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array Arr[] of N integers and an integer K, the task is to find if it is possible to make the count of even and odd elements equal by performing the following operations at most K times:

  • Choose any index i such that Arr[i] is even and divide it by 2.
  • Choose any index i such that Arr[i] is odd and multiply it by 2.

Examples:

Input: Arr[] = {1, 4, 8, 12}, K = 2 
Output: Yes
Explanation: Count of Odd = 1, Count of Even = 3. 
If we half 4  twice then 4 becomes 1 or if we half 12 twice then it becomes 3. 
It is possible to make even and odd count equal by performing 2 operations.

Input: Arr[] = {1, 2, 3, 4}, K = 0
Output: Yes

 

Approach: The idea to solve this problem is as follows:

Find the count of even and odd elements (say expressed as CE and CO respectively).

The number of elements needed to be modified = abs(CE - CO)/2.
An even character needed to be halved i times if its right most bit is at (i+1)th position from the right. And an odd element can be made even by multiplying it by 2 in a single operation.

Use this criteria to find the number of operations required and if it is at most K or not.

Follow the below steps to solve the problem:

  • If N is odd, return False.
  • Else Initialize a vector (say v) of size 32 with 0 to store the count of rightmost bits at a position, CE (Count of Even) = 0 and CO(Count of Odd) = 0.
  • Iterate through the array from 0 to N-1
    • Find CE and CO of Arr[]
    • Find the index of the rightmost set bit for every array element and increment that index value of the vector v.
    • If CE = CO, then no operations required to make counts equal.
  • If CO > CE, the result will be (CO - CE)/2. 
  • Otherwise, find required operations by iterating the vector.
  • Return true If the required operation is less than K. Else return false.

Below is the implementation of the above approach.

C++
// C++ code to implement the above approach

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

// Function to check if it is possible
// to make even and odd element count same
// using at most K operations
bool findCount(int* arr, int N, int K)
{
    // Edge Case
    if (N & 1) {
        return 0;
    }

    // Initialize the variables
    int Res, CE = 0, CO = 0;

    vector<int> v(32, 0);

    // Find the index of rightmost set bit
    // for every array element and increment
    // that index of vector, also find even
    // and odd count
    for (int i = 0; i < N; i++) {

        if (arr[i] & 1)
            CO++;

        else
            CE++;

        v[ffs(arr[i]) - 1]++;
    }

    // Condition is already true
    if (CE == CO) {
        Res = 0;
    }

    // Count of Even > Count of Odd
    else if (CE > CO) {

        int n = (CE - CO) / 2;
        Res = 0;

        // Find minimum operations to make the
        // even and odd count equal
        for (int i = 1; i < v.size(); i++) {

            if (n >= v[i]) {
                Res += v[i] * i;
                n = n - v[i];
            }
            else {
                Res += n * i;
                break;
            }
        }
    }

    // Count of Odd > Count of Even
    else {
        Res = (CO - CE) / 2;
    }

    return Res <= K;
}

// Driver Code
int main()
{

    int Arr[] = { 1, 4, 8, 12 };

    int N = sizeof(Arr) / sizeof(Arr[0]);
    int K = 2;

    // Function Call
    if (findCount(Arr, N, K))

        cout << "Yes" << endl;
    else
        cout << "No" << endl;

    return 0;
}
Java
// Java code to implement the above approach


import java.util.*;

class GFG{

// Function to check if it is possible
// to make even and odd element count same
// using at most K operations
static boolean findCount(int []arr, int N, int K)
{
    // Edge Case
    if ((N & 1)>0) {
        return false;
    }

    // Initialize the variables
    int Res, CE = 0, CO = 0;

    int []v = new int[32];

    // Find the index of rightmost set bit
    // for every array element and increment
    // that index of vector, also find even
    // and odd count
    for (int i = 0; i < N; i++) {

        if ((arr[i] & 1)>0)
            CO++;

        else
            CE++;

        v[arr[i] & (arr[i]-1) - 1]++;
    }

    // Condition is already true
    if (CE == CO) {
        Res = 0;
    }

    // Count of Even > Count of Odd
    else if (CE > CO) {

        int n = (CE - CO) / 2;
        Res = 0;

        // Find minimum operations to make the
        // even and odd count equal
        for (int i = 1; i < v.length; i++) {

            if (n >= v[i]) {
                Res += v[i] * i;
                n = n - v[i];
            }
            else {
                Res += n * i;
                break;
            }
        }
    }

    // Count of Odd > Count of Even
    else {
        Res = (CO - CE) / 2;
    }

    return Res <= K;
}

// Driver Code
public static void main(String[] args)
{

    int Arr[] = { 1, 4, 8, 12 };

    int N = Arr.length;
    int K = 2;

    // Function Call
    if (findCount(Arr, N, K))

        System.out.print("Yes" +"\n");
    else
        System.out.print("No" +"\n");

}
}

// This code contributed by shikhasingrajput
Python3
# Python code to implement the above approach

# Function to check if it is possible
# to make even and odd element count same
# using at most K operations


def findCount(arr, N, K):
    # Edge Case
    if ((N & 1) != 0):
        return 0
    # Initialize the variables
    Res = 0
    CE = 0
    CO = 0
    v = [0]*32
    # Find the index of rightmost set bit
    # for every array element and increment
    # that index of vector, also find even
    # and odd count
    for i in range(N):
        if ((arr[i] & 1) != 0):
            CO += 1
        else:
            CE += 1
        v[arr[i] & (arr[i]-1) - 1] += 1

        # Condition is already true
    if (CE == CO):
        Res = 0

    # Count of Even > Count of Odd
    elif (CE > CO):
        n = (CE - CO) / 2
        Res = 0
        # Find minimum operations to make the
        # even and odd count equal
        for i in range(1, len(v)):
            if (n >= v[i]):
                Res += (v[i] * i)
                n = n - v[i]
            else:
                Res += n * i
                break

    # Count of Odd > Count of Even
    else:
        Res = (CO - CE) / 2

    return Res <= K


# Driver Code
if __name__ == "__main__":
    Arr = [1, 4, 8, 12]
    N = len(Arr)
    K = 2

    # Function Call
    if findCount(Arr, N, K):
        print("Yes")
    else:
        print("No")

# This code is contributed by Rohit Pradhan
C#
// C# code to implement the above approach

using System;

public class GFG {

    // Function to check if it is possible
    // to make even and odd element count same
    // using at most K operations
    static bool findCount(int[] arr, int N, int K)
    {
        // Edge Case
        if ((N & 1) > 0) {
            return false;
        }

        // Initialize the variables
        int Res, CE = 0, CO = 0;

        int[] v = new int[32];

        // Find the index of rightmost set bit
        // for every array element and increment
        // that index of vector, also find even
        // and odd count
        for (int i = 0; i < N; i++) {
            if ((arr[i] & 1) > 0)
                CO++;
            else
                CE++;
            v[arr[i] & (arr[i] - 1) - 1]++;
        }

        // Condition is already true
        if (CE == CO) {
            Res = 0;
        }

        // Count of Even > Count of Odd
        else if (CE > CO) {

            int n = (CE - CO) / 2;
            Res = 0;

            // Find minimum operations to make the
            // even and odd count equal
            for (int i = 1; i < v.Length; i++) {

                if (n >= v[i]) {
                    Res += v[i] * i;
                    n = n - v[i];
                }
                else {
                    Res += n * i;
                    break;
                }
            }
        }

        // Count of Odd > Count of Even
        else {
            Res = (CO - CE) / 2;
        }

        return Res <= K;
    }

    static public void Main()
    {

        // Code
        int[] Arr = { 1, 4, 8, 12 };

        int N = Arr.Length;
        int K = 2;

        // Function Call
        if (findCount(Arr, N, K))
            Console.Write("Yes"
                          + "\n");
        else
            Console.Write("No"
                          + "\n");
    }
}

// This code contributed by lokeshmvs21.
JavaScript
    <script>
        // JavaScript code to implement the above approach

        // Function to find rightmost
        // set bit in given number.
        function ffs(n) {
            return Math.log2(n & -n) + 1;
        }

        // Function to check if it is possible
        // to make even and odd element count same
        // using at most K operations
        const findCount = (arr, N, K) => {
            // Edge Case
            if (N & 1) {
                return 0;
            }

            // Initialize the variables
            let Res, CE = 0, CO = 0;

            let v = new Array(32).fill(0);

            // Find the index of rightmost set bit
            // for every array element and increment
            // that index of vector, also find even
            // and odd count
            for (let i = 0; i < N; i++) {

                if (arr[i] & 1)
                    CO++;

                else
                    CE++;

                v[ffs(arr[i]) - 1]++;
            }

            // Condition is already true
            if (CE == CO) {
                Res = 0;
            }

            // Count of Even > Count of Odd
            else if (CE > CO) {

                let n = parseInt((CE - CO) / 2);
                Res = 0;

                // Find minimum operations to make the
                // even and odd count equal
                for (let i = 1; i < v.length; i++) {

                    if (n >= v[i]) {
                        Res += v[i] * i;
                        n = n - v[i];
                    }
                    else {
                        Res += n * i;
                        break;
                    }
                }
            }

            // Count of Odd > Count of Even
            else {
                Res = parseInt((CO - CE) / 2);
            }

            return Res <= K;
        }

        // Driver Code

        let Arr = [1, 4, 8, 12];

        let N = Arr.length;
        let K = 2;

        // Function Call
        if (findCount(Arr, N, K))

            document.write("Yes");
        else
            document.write("No");
    
            // This code is contributed by rakeshsahni
    
    </script>

Output
Yes

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


Next Article
Article Tags :
Practice Tags :

Similar Reads