VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-even-and-odd-count-of-elements-can-be-made-equal-in-array/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 5 Aug, 2022

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.


Output
Yes

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

Comment
Article Tags: