Find index of the element differing in parity with all other array elements

Given an array arr[] of size N (N > 3), the task is to find the position of the element that differs in parity (odd/even) with respect to all other array elements.Â
Note: It is guaranteed that there will always be a number that differs in parity from all other elements.
Examples:
Input: arr[] = {2, 4, 7, 8, 10}
Output: 2
Explanation: The only odd element in the array is 7 (= arr[2]). Therefore, required output is 2.Input: arr[] = {2, 1, 1}
Output: 0
Naive Approach: The simplest approach to solve this problem is to store all even and odd numbers with their indices in a Multimap and print the index of the element present in the Map having size 1. Follow the steps below to solve the problem:
- Initialize two Multimap, for even and odd numbers.
- Traverse the array and store array elements in their respective Multimaps along with their indices.
- Now find the Multimap with size equal to 1. Print the index of the array element stored in that Multimap.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the array// element which differs in parity// with the remaining array elementsint OddOneOut(int arr[], int N){Â
    // Multimaps to store even    // and odd numbers along    // with their indices    multimap<int, int> e, o;Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
        // If array element is even        if (arr[i] % 2 == 0) {            e.insert({ arr[i], i });        }Â
        // Otherwise        else {            o.insert({ arr[i], i });        }    }Â
    // If only one even element    // is present in the array    if (e.size() == 1) {        cout << e.begin()->second;    }Â
    // If only one odd element    // is present in the array    else {        cout << o.begin()->second;    }}Â
// Driver Codeint main(){    // Given array    int arr[] = { 2, 4, 7, 8, 10 };Â
    // Size of the array    int N = sizeof(arr) / sizeof(arr[0]);Â
    OddOneOut(arr, N);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG {Â
  // Function to print the array  // element which differs in parity  // with the remaining array elements  static void OddOneOut(int[] arr, int N)  {Â
    // Multimaps to store even    // and odd numbers along    // with their indices    HashMap<Integer, Integer> e      = new LinkedHashMap<Integer, Integer>();    HashMap<Integer, Integer> o      = new LinkedHashMap<Integer, Integer>();Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
      // If array element is even      if (arr[i] % 2 == 0) {        e.put(arr[i], i);      }Â
      // Otherwise      else {        o.put(arr[i], i);        ;      }    }Â
    // If only one even element    // is present in the array    if (e.size() == 1) {      Map.Entry<Integer, Integer> entry        = e.entrySet().iterator().next();      System.out.print(entry.getValue());    }Â
    // If only one odd element    // is present in the array    else {      Map.Entry<Integer, Integer> entry        = o.entrySet().iterator().next();      System.out.print(entry.getValue());    }  }Â
  // Driver Code  public static void main(String[] args)  {Â
    // Given array    int[] arr = { 2, 4, 7, 8, 10 };Â
    // Size of the array    int N = arr.length;Â
    OddOneOut(arr, N);  }}Â
// This code is contributed by phasing17. |
Python3
# Python3 program for the above approachÂ
# Function to print the array# element which differs in parity# with the remaining array elementsdef OddOneOut(arr, N) :Â
    # Multimaps to store even    # and odd numbers along    # with their indices    e, o = {}, {}Â
    # Traverse the array    for i in range(N) :Â
        # If array element is even        if (arr[i] % 2 == 0) :            e[arr[i]] = iÂ
        # Otherwise        else :            o[arr[i]] = iÂ
    # If only one even element    # is present in the array    if (len(e) == 1) :        print(list(e.values())[0] )Â
    # If only one odd element    # is present in the array    else :        print(list(o.values())[0] )Â
# Given arrayarr = [ 2, 4, 7, 8, 10 ]Â
# Size of the arrayN = len(arr)Â
OddOneOut(arr, N)Â
# This code is contributed by divyesh072019. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG {Â
  // Function to print the array  // element which differs in parity  // with the remaining array elements  static void OddOneOut(int[] arr, int N)  {Â
    // Multimaps to store even    // and odd numbers along    // with their indices    Dictionary<int, int> e = new Dictionary<int, int>();    Dictionary<int, int> o = new Dictionary<int, int>();Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
      // If array element is even      if (arr[i] % 2 == 0) {        e[arr[i]] = i;      }Â
      // Otherwise      else {        o[arr[i]] = i;      }    }Â
    // If only one even element    // is present in the array    if (e.Count == 1) {      Console.Write(e.First().Value);    }Â
    // If only one odd element    // is present in the array    else {      Console.Write(o.First().Value);    }  }Â
  // Driver Code  public static void Main(string[] args)  {Â
    // Given array    int[] arr = { 2, 4, 7, 8, 10 };Â
    // Size of the array    int N = arr.Length;Â
    OddOneOut(arr, N);  }}Â
// This code is contributed by chitranayal. |
Javascript
<script>// Javascript program for the above approachÂ
// Function to print the array// element which differs in parity// with the remaining array elementsfunction OddOneOut(arr,N){    // Multimaps to store even    // and odd numbers along    // with their indices    let e = new Map();    let o = new Map();      // Traverse the array    for (let i = 0; i < N; i++) {        // If array element is even      if (arr[i] % 2 == 0) {        e.set(arr[i] , i);      }        // Otherwise      else {        o.set(arr[i] , i);      }    }          // If only one even element    // is present in the array    if (e.size == 1) {        document.write(Array.from(e.values())[0])   ;           }      // If only one odd element    // is present in the array    else {    document.write(Array.from(o.values())[0])   ;           }}Â
// Driver Code// Given arraylet arr=[2, 4, 7, 8, 10];// Size of the arraylet N = arr.length;OddOneOut(arr, N);Â
Â
// This code is contributed by avanitrachhadiya2155</script> |
2
Â
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to keep a count of even and odd array elements in two variables and check which count is equal to 1. Follow the steps below to solve the problem:
- Maintain four variables even, odd, to keep count of even and odd array elements in the array, and lastOdd, lastEven to store the indices of the last odd and even array elements encountered.
- After traversing the array, if odd is found to be 1, then print lastOdd.
- Otherwise, print lastEven.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the element// which differs in parityint oddOneOut(int arr[], int N){    // Stores the count of odd and    // even array elements encountered    int odd = 0, even = 0;Â
    // Stores the indices of the last    // odd and even array elements encountered    int lastOdd = 0, lastEven = 0;Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
        // If array element is even        if (arr[i] % 2 == 0) {            even++;            lastEven = i;        }Â
        // Otherwise        else {            odd++;            lastOdd = i;        }    }Â
    // If only one odd element    // is present in the array    if (odd == 1) {        cout << lastOdd << endl;    }Â
    // If only one even element    // is present in the array    else {        cout << lastEven << endl;    }}Â
// Driver Codeint main(){    // Given array    int arr[] = { 2, 4, 7, 8, 10 };Â
    // Size of the array    int N = sizeof(arr) / sizeof(arr[0]);Â
    oddOneOut(arr, N);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{  // Function to print the element// which differs in paritystatic void oddOneOut(int arr[], int N){       // Stores the count of odd and    // even array elements encountered    int odd = 0, even = 0;Â
    // Stores the indices of the last    // odd and even array elements encountered    int lastOdd = 0, lastEven = 0;Â
    // Traverse the array    for (int i = 0; i < N; i++) {Â
        // If array element is even        if (arr[i] % 2 == 0) {            even++;            lastEven = i;        }Â
        // Otherwise        else {            odd++;            lastOdd = i;        }    }Â
    // If only one odd element    // is present in the array    if (odd == 1) {        System.out.println(lastOdd);    }Â
    // If only one even element    // is present in the array    else {       System.out.println(lastEven);    }}   // Driver Codepublic static void main(String args[]){       // Given array    int arr[] = { 2, 4, 7, 8, 10 };Â
    // Size of the array    int N = arr.length;    oddOneOut(arr, N);}}Â
// This code is contributed by jana_sayantan. |
Python3
# Python program for the above approachÂ
# Function to print the element# which differs in paritydef oddOneOut(arr, N) :         # Stores the count of odd and    # even array elements encountered    odd = 0    even = 0Â
    # Stores the indices of the last    # odd and even array elements encountered    lastOdd = 0    lastEven = 0Â
    # Traverse the array    for i in range(N):Â
        # If array element is even        if (arr[i] % 2 == 0) :            even += 1            lastEven = i                 # Otherwise        else :            odd += 1            lastOdd = i             # If only one odd element    # is present in the array    if (odd == 1) :        print(lastOdd)         # If only one even element    # is present in the array    else :        print(lastEven)     # Driver CodeÂ
# Given arrayarr = [ 2, 4, 7, 8, 10 ]Â
# Size of the arrayN = len(arr)Â
oddOneOut(arr, N)Â
# This code is contributed by susmitakundugoaldanga. |
C#
// C# program for the above approachusing System;class GFG{         // Function to print the element    // which differs in parity    static void oddOneOut(int[] arr, int N)    {               // Stores the count of odd and        // even array elements encountered        int odd = 0, even = 0;              // Stores the indices of the last        // odd and even array elements encountered        int lastOdd = 0, lastEven = 0;              // Traverse the array        for (int i = 0; i < N; i++)        {                  // If array element is even            if (arr[i] % 2 == 0)            {                even++;                lastEven = i;            }                  // Otherwise            else            {                odd++;                lastOdd = i;            }        }              // If only one odd element        // is present in the array        if (odd == 1)         {            Console.WriteLine(lastOdd);        }              // If only one even element        // is present in the array        else        {            Console.WriteLine(lastEven);        }    }Â
  // Driver code  static void Main()  {          // Given array    int[] arr = { 2, 4, 7, 8, 10 };      // Size of the array    int N = arr.Length;    oddOneOut(arr, N);  }}Â
// This code is contributed by divyeshrabadiya07. |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to print the element// which differs in parityfunction oddOneOut(arr, N){         // Stores the count of odd and    // even array elements encountered    let odd = 0, even = 0;       // Stores the indices of the last    // odd and even array elements encountered    let lastOdd = 0, lastEven = 0;       // Traverse the array    for(let i = 0; i < N; i++)    {                 // If array element is even        if (arr[i] % 2 == 0)        {            even++;            lastEven = i;        }           // Otherwise        else        {            odd++;            lastOdd = i;        }    }       // If only one odd element    // is present in the array    if (odd == 1)    {        document.write(lastOdd);    }       // If only one even element    // is present in the array    else    {        document.write(lastEven);    }}Â
// Driver codeÂ
// Given arraylet arr = [ 2, 4, 7, 8, 10 ];Â
// Size of the arraylet N = arr.length;Â
oddOneOut(arr, N);Â Â Â // This code is contributed by suresh07Â Â
</script> |
2
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



