Array Index with same count of even or odd numbers on both sides

Given an array of N integers. We need to find an index such that Frequency of Even numbers on its left side is equal to the frequency of even numbers on its right sides Or frequency of odd numbers on its left side is equal to the frequency of Odd numbers on its right sides. If No such index exist in an array print -1 Else print required index. Note-(If more than one index exist then return index that comes first)
Examples:Â Â
Input : arr[] = {4, 3, 2, 1, 2, 4}
Output : index = 2
Explanation: At index 2, there is one
odd number on its left and one odd on
its right.
Input : arr[] = { 1, 2, 4, 5, 8, 3, 12}
Output : index = 3
Method 1 : (Simple Approach)Â
Run two loops. For every element, count evens and odds on its left and right sides.Â
Implementation:
C++
// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <iostream>using namespace std;Â
// Function to find indexint findIndex(int arr[], int n) {Â
  for (int i = 0; i < n; i++) {    int odd_left = 0, even_left = 0;    int odd_right = 0, even_right = 0;Â
    // To count Even and Odd numbers of left side    for (int j = 0; j < i; j++) {      if (arr[j] % 2 == 0)        even_left++;      else        odd_left++;    }Â
    // To count Even and Odd numbers of right side    for (int k = n - 1; k > i; k--) {      if (arr[k] % 2 == 0)        even_right++;      else        odd_right++;    }Â
    // To check Even Or Odd of Both sides are equal or not    if (even_right == even_left || odd_right == odd_left)      return i;  }Â
  return -1;}Â
// Driver's Functionint main() {Â Â int arr[] = {4, 3, 2, 1, 2};Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â int index = findIndex(arr, n);Â
  ((index == -1) ? cout << "-1" :           cout << "index = " << index);  return 0;} |
Java
// Java program to find// an index which has// same number of even// elements on left and// right, Or same number// of odd elements on// left and right.Â
class GFG{Â
// Function to find indexstatic int findIndex(int arr[], int n) {Â
for (int i = 0; i < n; i++) {Â
    int odd_left = 0, even_left = 0;    int odd_right = 0, even_right = 0;Â
    // To count Even and Odd        // numbers of left side    for (int j = 0; j < i; j++) {    if (arr[j] % 2 == 0)        even_left++;    else        odd_left++;    }Â
    // To count Even and Odd        // numbers of right side    for (int k = n - 1; k > i; k--) {    if (arr[k] % 2 == 0)        even_right++;    else        odd_right++;    }Â
    // To check Even Or Odd of Both        // sides are equal or not    if (even_right == even_left || odd_right == odd_left)    return i;}Â
return -1;Â
}Â
// Driver's Functionpublic static void main(String[] args) {Â
int arr[] = {4, 3, 2, 1, 2};int n = arr.length;int index = findIndex(arr, n);Â
if (index == -1) Â Â Â Â System.out.println("-1"); else{Â Â Â Â System.out.print("index = ");Â Â Â Â System.out.print(index);}}}Â
// This code is contributed by// Smitha Dinesh Semwal |
Python3
'''Python program to find   an index which has   same number of even   elements on left and   right, Or same number   of odd elements on   left and right.'''  Â
  # Function to find indexdef findIndex(arr,n):Â
    for i in range(n):          odd_left = 0        even_left = 0        odd_right = 0        even_right = 0          # To count Even and Odd        # numbers of left side        for j in range(i):            if (arr[j] % 2 == 0):                even_left=even_left+1            else:                odd_left=odd_left+1               # To count Even and Odd        # numbers of right side        for k in range(n - 1, i, -1):            if (arr[k] % 2 == 0):                even_right=even_right+1            else:                odd_right=odd_right+1               # To check Even Or Odd of Both        # sides are equal or not        if (even_right == even_left and odd_right == odd_left):            return i      return -1  Â
  # Driver's FunctionÂ
arr = [4, 3, 2, 1, 2]n = len(arr)index = findIndex(arr, n)Â Â if (index == -1):Â Â Â Â print("-1") else:Â Â Â Â print("index = ", index)Â
Â
Â
# This code is contributed# by Anant Agarwal. |
C#
// C# program to find an index which has// same number of even elements on left // and right, Or same number of odd // elements on left and right.using System;Â
class GFG{Â
    // Function to find index    static int findIndex(int []arr, int n) {             for (int i = 0; i < n; i++) {                     int odd_left = 0, even_left = 0;            int odd_right = 0, even_right = 0;                     // To count Even and Odd            // numbers of left side            for (int j = 0; j < i; j++) {                if (arr[j] % 2 == 0)                    even_left++;                else                    odd_left++;            }                     // To count Even and Odd            // numbers of right side            for (int k = n - 1; k > i; k--) {                if (arr[k] % 2 == 0)                    even_right++;                else                    odd_right++;            }                     // To check Even Or Odd of Both            // sides are equal or not            if (even_right == even_left ||                        odd_right == odd_left)                return i;        }                 return -1;    }         // Driver's Function    public static void Main() {             int []arr = {4, 3, 2, 1, 2};        int n = arr.Length;                 int index = findIndex(arr, n);                 if (index == -1)             Console.Write("-1");         else{            Console.Write("index = ");            Console.Write(index);        }    }}Â
// This code is contributed by vt_m. |
PHP
<?php// PHP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.Â
// Function to find indexfunction findIndex($arr, $n) {Â
    for ($i = 0; $i < $n; $i++)    {        $odd_left = 0;         $even_left = 0;        $odd_right = 0;         $even_right = 0;Â
        // To count Even and Odd         // numbers of left side        for ($j = 0; $j < $i; $j++)        {            if ($arr[$j] % 2 == 0)                $even_left++;            else                $odd_left++;        }Â
            // To count Even and Odd             // numbers of right side            for ($k = $n - 1; $k > $i; $k--)            {                if ($arr[$k] % 2 == 0)                    $even_right++;                else                    $odd_right++;            }Â
        // To check Even Or Odd of        // Both sides are equal or not        if ($even_right == $even_left ||                 $odd_right == $odd_left)        return $i;    }Â
    return -1;}Â
// Drivers Code{    $arr = array(4, 3, 2, 1, 2);    $n = sizeof($arr) / sizeof($arr[0]);    $index = findIndex($arr, $n);         if($index == -1)     echo "-1";    else    echo ("index = $index" );    return 0;}Â
// This code is contributed by nitin mittal.?> |
Javascript
<script>Â
// Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.Â
Â
// Function to find indexfunction findIndex(arr, n) {Â
for (let i = 0; i < n; i++) {Â Â Â Â let odd_left = 0, even_left = 0;Â Â Â Â let odd_right = 0, even_right = 0;Â
    // To count Even and Odd numbers of left side    for (let j = 0; j < i; j++) {    if (arr[j] % 2 == 0)        even_left++;    else        odd_left++;    }Â
    // To count Even and Odd numbers of right side    for (let k = n - 1; k > i; k--) {    if (arr[k] % 2 == 0)        even_right++;    else        odd_right++;    }Â
    // To check Even Or Odd of Both sides are equal or not    if (even_right == even_left || odd_right == odd_left)    return i;}Â
return -1;}Â
// Driver's FunctionÂ
let arr = [4, 3, 2, 1, 2];let n = arr.length;let index = findIndex(arr, n);Â
if (index == -1) Â Â Â Â Â Â Â Â Â Â Â Â document.write("-1"); Â Â Â Â Â Â Â Â else{Â Â Â Â Â Â Â Â Â Â Â Â document.write("index = ");Â Â Â Â Â Â Â Â Â Â Â Â document.write(index);Â Â Â Â Â Â Â Â }Â
Â
//This code is contributed by Mayank Tyagi</script> |
index = 2
Â
Time Complexity : O(n*n)Â
Auxiliary Space : O(1)Â
Method 2:(Efficient solution)Â
- Â Create two vectors of pair types i.e v_left and v_rightÂ
- v_left[i] stores the frequency of odd and even numbers of its left sidesÂ
- Â v_right[i] stores the frequency of odd and even numbers of its right sidesÂ
- Â Now check (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second)Â
if True return i - At last if no such index exist return -1Â
Implementation:
C++
// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <bits/stdc++.h>#include <iostream>using namespace std;Â
// Function to Find indexint Find_Index(int n, int arr[]) {Â
  int odd = 0, even = 0;Â
  // Create two vectors of pair type  vector<pair<int, int>> v_left, v_right;Â
  v_left.push_back(make_pair(odd, even));  for (int i = 0; i < n - 1; i++) {    if (arr[i] % 2 == 0)      even++;    else      odd++;Â
    v_left.push_back(make_pair(odd, even));  }Â
  odd = 0, even = 0;  v_right.push_back(make_pair(odd, even));  for (int i = n - 1; i > 0; i--) {    if (arr[i] % 2 == 0)      even++;    else      odd++;Â
    v_right.push_back(make_pair(odd, even));  }Â
  reverse(v_right.begin(), v_right.end());Â
  for (int i = 0; i < v_left.size(); i++) {Â
    // To check even or odd of Both sides are     // equal or not    if (v_left[i].first == v_right[i].first ||        v_left[i].second == v_right[i].second)      return i;  }  return -1;}Â
// Driver's Functionint main() {Â Â int arr[] = {4, 3, 2, 1, 2};Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â int index = Find_Index(n, arr);Â Â ((index == -1) ? cout << "-1" : cout << "index = " << index);Â Â return 0;} |
Java
// Java program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.import java.util.*;Â
class GFG{Â
    public static class pair    {Â
        int first, second;Â
        pair(int f, int s)         {            first = f;            second = s;        }    };Â
    // Function to Find index    static int Find_Index(int n, int arr[])     {Â
        int odd = 0, even = 0;Â
        // Create two vectors of pair type        Vector<pair> v_left = new Vector<>();;        Vector<pair> v_right = new Vector<>();Â
        v_left.add(new pair(odd, even));        for (int i = 0; i < n - 1; i++)         {            if (arr[i] % 2 == 0)             {                even++;            }             else            {                odd++;            }Â
            v_left.add(new pair(odd, even));        }Â
        odd = 0;        even = 0;        v_right.add(new pair(odd, even));        for (int i = n - 1; i > 0; i--)        {            if (arr[i] % 2 == 0)            {                even++;            }             else            {                odd++;            }Â
            v_right.add(new pair(odd, even));        }        Collections.reverse(v_right);Â
        for (int i = 0; i < v_left.size(); i++)        {Â
            // To check even or odd of Both sides are             // equal or not            if (v_left.get(i).first == v_right.get(i).first                    || v_left.get(i).second == v_right.get(i).second)            {                return i;            }        }        return -1;    }Â
    // Driver code    public static void main(String[] args)     {        int arr[] = {4, 3, 2, 1, 2};        int n = arr.length;        int index = Find_Index(n, arr);        if (index == -1)        {            System.out.println("-1");        }        else        {            System.out.println("index = " + index);        }    }}Â
/* This code contributed by PrinciRaj1992 */ |
Python3
# Python program to find an index which has# same number of even elements on left and# right, Or same number of odd elements on# left and right.class pair:    def __init__(self, f, s):        self.first = f        self.second = sÂ
# Function to Find indexdef Find_Index(n, arr):Â
    odd, even = 0, 0Â
    # Create two vectors of pair type    v_left = []    v_right = []Â
    v_left.append(pair(odd, even))    for i in range(n-1):Â
        if (arr[i] % 2 == 0):            even += 1                     else:            odd += 1Â
        v_left.append(pair(odd, even))Â
    odd = 0    even = 0    v_right.append(pair(odd, even))    for i in range(n-1,0,-1):        if (arr[i] % 2 == 0):            even += 1        else:            odd += 1Â
        v_right.append(pair(odd, even))             v_right = v_right[::-1]Â
    for i in range(len(v_left)):Â
        # To check even or odd of Both sides are        # equal or not        if (v_left[i].first == v_right[i].first or v_left[i].second == v_right[i].second):            return i             return -1Â
# Driver codearr = [4, 3, 2, 1, 2]n = len(arr)index = Find_Index(n, arr)if (index == -1):Â Â Â Â print("-1")else:Â Â Â Â print("index = " + str(index))Â
# This code is contributed by shinjanpatra |
C#
// C# program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.using System;using System.Collections.Generic;Â
class GFG{    public class pair    {        public int first, second;Â
        public pair(int f, int s)         {            first = f;            second = s;        }    };Â
    // Function to Find index    static int Find_Index(int n, int []arr)     {        int odd = 0, even = 0;Â
        // Create two vectors of pair type        List<pair> v_left = new List<pair>();;        List<pair> v_right = new List<pair>();Â
        v_left.Add(new pair(odd, even));        for (int i = 0; i < n - 1; i++)         {            if (arr[i] % 2 == 0)             {                even++;            }             else            {                odd++;            }Â
            v_left.Add(new pair(odd, even));        }Â
        odd = 0;        even = 0;        v_right.Add(new pair(odd, even));        for (int i = n - 1; i > 0; i--)        {            if (arr[i] % 2 == 0)            {                even++;            }             else            {                odd++;            }Â
            v_right.Add(new pair(odd, even));        }        v_right.Reverse();Â
        for (int i = 0; i < v_left.Count; i++)        {Â
            // To check even or odd of Both sides are             // equal or not            if (v_left[i].first == v_right[i].first ||                 v_left[i].second == v_right[i].second)            {                return i;            }        }        return -1;    }Â
    // Driver code    public static void Main(String[] args)     {        int []arr = {4, 3, 2, 1, 2};        int n = arr.Length;        int index = Find_Index(n, arr);        if (index == -1)        {            Console.WriteLine("-1");        }        else        {            Console.WriteLine("index = " + index);        }    }}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>// Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.class pair{Â Â Â Â constructor(f,s)Â Â Â Â {Â Â Â Â Â Â Â Â this.first = f;Â Â Â Â Â Â Â Â this.second = s;Â Â Â Â }}Â
// Function to Find indexfunction Find_Index(n,arr){    let odd = 0, even = 0;          // Create two vectors of pair type        let v_left = [];        let v_right = [];          v_left.push(new pair(odd, even));        for (let i = 0; i < n - 1; i++)        {            if (arr[i] % 2 == 0)            {                even++;            }            else            {                odd++;            }              v_left.push(new pair(odd, even));        }          odd = 0;        even = 0;        v_right.push(new pair(odd, even));        for (let i = n - 1; i > 0; i--)        {            if (arr[i] % 2 == 0)            {                even++;            }            else            {                odd++;            }              v_right.push(new pair(odd, even));        }        v_right.reverse();          for (let i = 0; i < v_left.length; i++)        {              // To check even or odd of Both sides are            // equal or not            if (v_left[i].first == v_right[i].first                    || v_left[i].second == v_right[i].second)            {                return i;            }        }        return -1;}Â
// Driver codelet arr = [4, 3, 2, 1, 2];let n = arr.length;let index = Find_Index(n, arr);if (index == -1){Â Â Â Â document.write("-1");}else{Â Â Â Â document.write("index = " + index);}Â
// This code is contributed by rag2127</script> |
index = 2
Â
Time Complexity : O(n)Â
Auxiliary Space : O(n)Â
Further optimization : We can optimize the space used in the program. Instead of making vectors of pairs, we can make vectors of integers. We can use the fact that number of odd elements is equal total elements minus total number of even elements. Similarly, number of even elements is equal total elements minus total number of odd elements.Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



