Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if all elements of the given array can be made 0 by decrementing value in pairs
Next article icon

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
Check if all elements of the given array can be made 0 by decrementing value in pairs
author
akashjha2671
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • setBitCount
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • Check if Array Elemnts can be Made Equal with Given Operations
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
    6 min read
  • Count number of even and odd length elements in an Array
    Given an array arr[] of integers of size N, the task is to find the number elements of the array having even and odd length.Examples: Input: arr[] = {14, 735, 3333, 223222} Output: Number of even length elements = 3 Number of odd length elements = 1 Input: arr[] = {1121, 322, 32, 14783, 44} Output:
    5 min read
  • Check if all elements of a Circular Array can be made equal by increments of adjacent pairs
    Given a circular array arr[] of size N, the task is to check if it is possible to make all array elements of the circular array equal by increasing pairs of adjacent elements by 1. Examples: Input: N = 4, arr[] = {2, 1, 3, 4} Output:YesExplanation:Step 1: {2, 1, 3, 4} -> {3, 2, 3, 4}Step 2: {3, 2
    5 min read
  • Minimize increments required to make count of even and odd array elements equal
    Given an array arr[] of size N, the task is to find the minimum increments by 1 required to be performed on the array elements such that the count of even and odd integers in the given array becomes equal. If it is not possible, then print "-1". Examples: Input: arr[] = {1, 3, 4, 9}Output: 1Explanat
    6 min read
  • Check if all elements of the given array can be made 0 by decrementing value in pairs
    Given an array arr[] consisting of positive integers, the task is to check if all elements of the given array can be made 0 by performing the following operation: Choose two indices i and j such that i != j and subtract 1 from both arr[i] and arr[j]The above operation can be performed any number of
    6 min read
  • Check if sum of exactly K elements of the Array can be odd or not
    Given an array, arr[] and an integer K. Check whether it is possible to get an odd sum by choosing exactly K elements of the array. Examples: Input: arr[] = {1, 2, 3}, K = 2 Output: Possible Explanation: {2, 3} ⇾ 2 + 3 = 5 Input: arr[] = {2, 2, 4, 2}, K = 4 Output: Not Possible Explanation: {2, 2, 4
    10 min read
  • Count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element
    Given an array arr[] of length N, the task is to find the count of array indices such that removing an element from these indices makes the Bitwise xor of odd-indexed elements and even-indexed (1-based indexing) elements are equal. Examples: Input: arr[] = {1, 0, 1, 0, 1}, N = 5Output: 3Explanation:
    10 min read
  • Ways to make sum of odd and even indexed elements equal by removing an array element
    Given an array, arr[] of size n, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. Examples: Input: arr[] = [ 2, 1, 6, 4 ] Output: 1 Explanation: Removing arr[1] from the array modifies
    10 min read
  • Absolute Difference of even and odd indexed elements in an Array
    Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Out
    6 min read
  • Check if every index i has an index j such that sum of elements in both directions are equal
    Given a circular array of size N. The task is to check if, for every index, i starting from 0 to N-1, there exists an index j that is not equal to i such that the sum of all the numbers in the clockwise direction from i to j is equal to the sum of all numbers in the anticlockwise direction from i to
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences