Skip to content
Related Articles

Related Articles

First element that appears even number of times in an array
  • Difficulty Level : Medium
  • Last Updated : 28 Mar, 2019

Given an array, find the first element that appears even number of times in the array. It returns the element if exists otherwise returns 0.

Examples:

Input : arr[] = {1, 5, 4, 7, 4, 1, 5, 7, 1, 5};
Output : 4
Explanation, 4 is the first element that appears even number of times.

Input : arr[] = {2, 4, 6, 8, 1, 6};
Output : 6
Explanation, 6 is the first element that appears even number of times

A Simple solution is to consider every element one by one. For every element, start counting the frequency, the first element whose count is even gives the result. Time complexity of this solution is O(n^{2}).



An Efficient solution can solve this problem using hash map having O(n) time and O(n) extra space as:

    For each element a[i] of the array, do the following:

  • If a[i] is not present in the hash map, insert it in hash map as pair (a[i], false).
  • If a[i] is present in the hash map and value is true, toggle it to false.
  • If a[i] is present in the hash map and value is false, toggle it to true.
  • To find the first element appearing even number of times, traverse the array again and find a[i] with value true and return.

C++




// C++ code to find the first element
// that appears even number times
#include <bits/stdc++.h>
using namespace std;
int firstEven(int arr[], int n)
{
  
    unordered_map<int, bool> map1;
  
    for (int i = 0; i < n; i++)
    {
  
        // first time occurred
        if (map1.find(arr[i]) == map1.end())
            map1.insert(pair <int,bool> (arr[i],false));
  
        // toggle for repeated occurrence
        else
        {
            bool val = map1.find(arr[i])->second;
            if (val == true)
                map1.find(arr[i])->second = false;
            else
                map1.find(arr[i])->second = true;
        }
    }
  
    int j = 0;
    for (j = 0; j < n; j++)
    {
  
        // first integer with true value
        if (map1.find(arr[j])->second == true)
            break;
    }
  
    return arr[j];
}
  
// Driver code
int main()
{
    int arr[] = { 2, 4, 6, 8, 1, 6 };
    cout << firstEven(arr, 6);
    return 0;
}


Java




// JAVA code to find the first element
// that appears even number times
import java.util.*;
class GFG {
    public static int firstEven(int arr[], int n)
    {
  
        HashMap<Integer, Boolean> map = 
                 new HashMap<Integer, Boolean>();
  
        for (int i = 0; i < n; i++) {
  
            // first time occurred
            if (map.get(arr[i]) == null
                map.put(arr[i], false);
              
            // toggle for repeated occurrence
            else {
                boolean val = map.get(arr[i]);
                if (val == true)
                    map.put(arr[i], false);
                else
                    map.put(arr[i], true);
            }
        }
  
        int j = 0;
        for (j = 0; j < n; j++) {
  
            // first integer with true value
            if (map.get(arr[j]) == true)
                break;
        }
  
        return arr[j];
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 4, 6, 8, 1, 6 };
        int n = arr.length;
        System.out.println(firstEven(arr, n));
    }
}


Python3




# Python3 code to find the first element 
# that appears even number times 
def firstEven(arr, n): 
  
    map1 = {} 
    for i in range(0, n): 
      
        # first time occurred 
        if arr[i] not in map1: 
            map1[arr[i]] = False
  
        # toggle for repeated occurrence 
        else:
            map1[arr[i]] = not map1[arr[i]]
  
    for j in range(0, n): 
      
        # first integer with true value 
        if map1[arr[j]] == True
            break
      
    return arr[j] 
  
# Driver code 
if __name__ == "__main__":
  
    arr = [2, 4, 6, 8, 1, 6
    print(firstEven(arr, 6))
  
# This code is contributed 
# by Rituraj Jain


C#




// C# code to find the first element
// that appears even number times
using System;
using System.Collections.Generic;
  
class GFG 
{
    static int firstEven(int []arr, 
                         int n)
    {
        var map = new Dictionary<int
                                 string>();
          
        var hash = new HashSet<int>(arr);
          
        foreach (int a in hash)
            map.Add(a, "null");
              
        for (int i = 0; i < n; i++) 
        {
  
            // first time occurred
            if (map[arr[i]].Equals("null"))
                map[arr[i]] = "false";
              
            // toggle for repeated
            // occurrence
            else 
            {
                string val = map[arr[i]];
                if (val.Equals("true"))
                    map[arr[i]] = "false";
                else
                    map[arr[i]] = "true";
            }
        }
  
        int j = 0;
        for (j = 0; j < n; j++)
        {
  
            // first integer with
            // true value
            if (map[arr[j]].Equals("true"))
                break;
        }
        return arr[j];
    }
  
    // Driver code
    static void Main()
    {
        int []arr = new int[]{ 2, 4, 6,
                               8, 1, 6 };
        int n = arr.Length;
        Console.Write(firstEven(arr, n));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)


Output:

6

Time Complexity: O(n)
Auxiliary Space : O(n)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :