C++ program for the Array Index with same count of even or odd numbers on both sides?

C++Server Side ProgrammingProgramming

Finding the array index with the same count of even or odd number is a number that has equal number of either numbers or odd number on both sides of it i.e. no.s at left = no.s right.

Here, we need a few definitions that are related to the concept,

Array − A container of elements of same data type.

Array Index − The position of an element is called its index. Index of array always start from 0.

Even number − A number that is divisible by 2.

Odd number − A number that is not divisible by 2.

A whole number can either be an even number or an odd number.

Now, lets see an example that will make the concept more clear.

Input: arr[] = {4, 3, 2, 1, 2}
Output : 2

Explanation

At index 2, there is one odd number on its left and one odd on its right.

We have an array of n integers where to find the index of array element in such a way that it has even number even number of element on its left side and an even number of elements on its right side or we have to find frequency of odd number of element on its left side it is equal to the frequency of odd number of element in it there right side if there is no such condition so we have to who written ok print -1 if there is this type of condition then we have to print its index

Algorithm

To calculate the index of element with count of even or odd numbers on both sides, we need to find the number of elements on the left of and on the right of the given element.

Given array arr[] , n number of elements of array.

Step 1 : For i -> 0 to n, follow step 2 - 5:
Step 2: initialise e_l, o_l, e_r, o_r to 0.
Step 3: for j -> o to i
   Step 3.1 : count values for e_l and o_l.
Step 4: for j -> i+1 to n
   Step 4.1 : count values for e_r and o_r.
Step 5: if(e_l == e_r) or (o_l == e_r ) , print i.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[] = {4, 3, 2, 1, 2};
   int n = 5;
   cout<<"The array is : ";
   for(int i = 0; i < n; i++) {
      cout<<arr[i]<<" ";
   }
   cout<<"\nThe index of the element with the same count of even or odd numbers on both sides = ";
   for (int i = 0; i < n; i++) {
      int o_l = 0, e_l = 0;
      int o_r = 0, e_r = 0;
   for (int j = 0; j < i; j++) {
      if (arr[j] % 2 == 0)
         e_l++;
      else
         o_l++;
   }
   for (int k = n - 1; k > i; k--) {
      if (arr[k] % 2 == 0)
         e_r++;
      else
         o_r++;
   }
   if (e_r == e_l || o_r == o_l)
      cout<<i<<endl;
   }
   return 0;
}

Output

The array is : 4 3 2 1 2
The index of the element with the same count of even or odd numbers on both sides = 2
raja
Published on 04-Oct-2019 08:26:13
Advertisements