Open In App

Number occurring odd number of times

Last Updated : 30 Aug, 2025
Comments
Improve
Suggest changes
76 Likes
Like
Report

Given an array arr[] of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times.

Examples : 

Input : arr[]= [1, 2, 3, 2, 3, 1, 3]
Output : 3

Input : arr[] = [5, 7, 2, 7, 5, 2, 5]
Output : 5

[Naive Approach] Using Nested Loop

A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and the inner loop counts the number of occurrences of the element picked by the outer loop.

C++
#include<iostream>
#include <vector>
using namespace std;

// Function to find the element 
// occurring odd number of times
int getOddOccurrence(vector<int>&arr, int n)
{
    for (int i = 0; i < n ; i++) {
        
        int count = 0;
        
        for (int j = 0; j < n; j++)
        {
            if (arr[i] == arr[j])
                count++;
        }
        if (count % 2 != 0)
            return arr[i];
    }
    return -1;
}


int main()
    {
       vector<int>arr { 2, 3, 5, 4, 5, 2,
                      4, 3, 5, 2, 4, 4, 2 };
        int n = arr.size();
        cout << getOddOccurrence(arr, n);

        return 0;
    }
Java
import java.util.*;

public class Main {

    // Function to find the element 
    // occurring odd number of times
    static int getOddOccurrence(ArrayList<Integer> arr, int n) {
        for (int i = 0; i < n; i++) {

            int count = 0;

            for (int j = 0; j < n; j++) {
                if (arr.get(i).equals(arr.get(j)))
                    count++;
            }

            if (count % 2 != 0)
                return arr.get(i);
        }
        return -1;
    }

    public static void main(String[] args) {
        ArrayList<Integer> arr = new 
            ArrayList<>(Arrays.asList
               (2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2));
        int n = arr.size();

        System.out.println(getOddOccurrence(arr, n));
    }
}
Python
# function to find the element occurring odd
# number of times
def getOddOccurrence(arr, arr_size):
    
    for i in range(0,arr_size):
        count = 0
        for j in range(0, arr_size):
            if arr[i] == arr[j]:
                count+=1
            
        if (count % 2 != 0):
            return arr[i]
        
    return -1
    
    
if __name__ == "__main__":
    arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ]
    n = len(arr)
    print(getOddOccurrence(arr, n))
C#
using System;
using System.Collections.Generic;

class GFG
{
    // Function to find the element 
    // occurring odd number of times
    static int GetOddOccurrence(List<int> arr, int arr_size)
    {
        for (int i = 0; i < arr_size; i++)
        {
            int count = 0;

            for (int j = 0; j < arr_size; j++)
            {
                if (arr[i] == arr[j])
                    count++;
            }
            if (count % 2 != 0)
                return arr[i];
        }
        return -1;
    }

    public static void Main()
    {
        List<int> arr = new List<int> { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
        int n = arr.Count;
        Console.Write(GetOddOccurrence(arr, n));
    }
}
JavaScript
// Function to find the element 
// occurring odd number of times 
function getOddOccurrence(arr, arr_size) 
{ 
    for (let i = 0; i < arr_size; i++) { 
        
        let count = 0; 
        
        for (let j = 0; j < arr_size; j++) 
        { 
            if (arr[i] == arr[j]) 
                count++; 
        } 
        if (count % 2 != 0) 
            return arr[i]; 
    } 
    return -1; 
} 

//Driver Code 
        let arr = [ 2, 3, 5, 4, 5, 2, 
                    4, 3, 5, 2, 4, 4, 2 ]; 
        let n = arr.length; 
        console.log(getOddOccurrence(arr, n)); 
PHP
<?php
// Function to find the element 
// occurring odd number of times
function getOddOccurrence(&$arr, $arr_size)
{
    $count = 0;
    for ($i = 0; 
         $i < $arr_size; $i++) 
    {
        
        for ($j = 0;
             $j < $arr_size; $j++)
        {
            if ($arr[$i] == $arr[$j])
                $count++;
        }
        if ($count % 2 != 0)
            return $arr[$i];
    }
    return -1;
}


$arr = array(2, 3, 5, 4, 5, 2, 
             4, 3, 5, 2, 4, 4, 2);
$n = sizeof($arr);
echo(getOddOccurrence($arr, $n));

?>

Output
5

Time Complexity: O(n^2)
Auxiliary Space: O(1)

[Another Approach]Using Hashing

A Better Solution is to use Hashing. Use array elements as a key and their counts as values. Create an empty hash table. One by one traverse the given array elements and store counts.

C++
#include <iostream>
#include<vector>
#include <unordered_map>
using namespace std;

// function to find the element 
// occurring odd number of times 
int getOddOccurrence(vector<int>&arr,int size)
{
    
    // Defining HashMap in C++
    unordered_map<int, int> hash;

    // Putting all elements into the HashMap 
    for(int i = 0; i < size; i++)
    {
        hash[arr[i]]++;
    }
    // Iterate through HashMap to check an element
    // occurring odd number of times and return it
    for(auto i : hash)
    {
        if(i.second % 2 != 0)
        {
            return i.first;
        }
    }
    return -1;
}

int main() 
{ 
    vector<int>arr { 2, 3, 5, 4, 5, 2, 4,
                    3, 5, 2, 4, 4, 2 }; 
    int n = arr.size();
    cout << getOddOccurrence(arr, n); 

    return 0; 
} 
Java
import java.util.*;

class OddOccurrence {

    // Function to find the element
    // occurring odd number of times
    static int getOddOccurrence(ArrayList<Integer> arr, int n) {
        for (int i = 0; i < n; i++) {
            int count = 0;

            // Count occurrences of arr.get(i)
            for (int j = 0; j < n; j++) {
                if (arr.get(i).equals(arr.get(j)))
                    count++;
            }

            // If count is odd, return it
            if (count % 2 != 0)
                return arr.get(i);
        }
        return -1; // No odd occurrence found
    }

    public static void main(String[] args) {
        ArrayList<Integer> arr = 
        new ArrayList<>(Arrays.asList(2, 3, 5, 4, 5, 2,
                                  4, 3, 5, 2, 4, 4, 2));
        int n = arr.size();
        System.out.println(getOddOccurrence(arr, n));
    }
}
Python
# function to find the element 
# occurring odd number of times 
def getOddOccurrence(arr,size):
     
    # Defining HashMap in C++
    Hash=dict()
 
    # Putting all elements into the HashMap 
    for i in range(size):
        Hash[arr[i]]=Hash.get(arr[i],0) + 1;
    
    # Iterate through HashMap to check an element
    # occurring odd number of times and return it
    for i in Hash:

        if(Hash[i]% 2 != 0):
            return i
    return -1

 
if __name__ == "__main__":
    arr=[2, 3, 5, 4, 5, 2, 4,3, 5, 2, 4, 4, 2]
    n = len(arr)
    print(getOddOccurrence(arr, n)) 
C#
using System;
using System.Collections.Generic;

public class GFG
{
    // Function to find the element
    // occurring odd number of times
    static int GetOddOccurrence(List<int> arr, int n)
    {
        Dictionary<int, int> hmap = new Dictionary<int, int>();

        // Putting all elements into the Dictionary
        for (int i = 0; i < n; i++)
        {
            if (hmap.ContainsKey(arr[i]))
            {
                int val = hmap[arr[i]];

                // If element is already present then 
                // increase its count
                hmap[arr[i]] = val + 1;
            }
            else
            {
                // If element is not present then add 
                // it with count = 1
                hmap.Add(arr[i], 1);
            }
        }

        // Checking for odd occurrence of each
        // element present in the Dictionary
        foreach (KeyValuePair<int, int> entry in hmap)
        {
            if (entry.Value % 2 != 0)
            {
                return entry.Key;
            }
        }
        return -1;
    }

    // Driver code
    public static void Main(String[] args)
    {
        List<int> arr = new List<int> 
        { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
        int n = arr.Count;
        Console.WriteLine(GetOddOccurrence(arr, n));
    }
}
JavaScript
    // function to find the element occurring odd
    // number of times
    function getOddOccurrence(arr,n)
    {
        let hmap = new Map();
         
        // Putting all elements into the HashMap
        for(let i = 0; i < n; i++)
        {
            if(hmap.has(arr[i]))
            {
                let val = hmap.get(arr[i]);
                // If array element is already present then
                // increase the count of that element.
                hmap.set(arr[i], val + 1);
            }
            else
            {     
                // if array element is not present then put
                // element into the HashMap and initialize
                // the count to one.
                hmap.set(arr[i], 1);
            }
        }
        
 
        // Checking for odd occurrence of
        //  each element present in the HashMap
        for(let [key, value] of hmap.entries())
        {
            //console.log(hmap[a]+"<br>")
            if(hmap.get(key) % 2 != 0)
                return key;
        }
        return -1;
    }
    
    // Driver code   
    let arr=[2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2];
    let n = arr.length;
    console.log(getOddOccurrence(arr, n));
    
    
    // This code is contributed by unknown2108

Output
5

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

[Expected Approach] Using Bit Manipulation

The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring elements. 

Here ^ is the XOR operators;
Note : x ^ 0 = x
x ^ y=y ^ x (Commutative property holds)
(x ^ y) ^ z = x ^ ( y ^ z) (Distributive property holds)
x ^ x=0
C++
#include <iostream>
#include <vector>
using namespace std;

// Function to find element occurring odd number of times
int getOddOccurrence(vector<int>& ar)
{
    int res = 0; 
    for (int i = 0; i < ar.size(); i++)     
        res ^= ar[i];
    
    return res;
}

int main()
{
    vector<int> ar = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};

    // Function calling
    cout << getOddOccurrence(ar);
    
    return 0;
}
C
#include <stdio.h>

// Function to find element occurring
// odd number of times
int getOddOccurrence(int ar[], int ar_size)
{
    int res = 0; 
    for (int i = 0; i < ar_size; i++)     
        res = res ^ ar[i];
    
    return res;
}

int main()
{
    int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
    int n = sizeof(ar) / sizeof(ar[0]);
    
    // Function calling
    printf("%d", getOddOccurrence(ar, n));
    return 0;
}
Java
import java.util.*;

public class Main {

    // Function to find element occurring odd number of times
    static int getOddOccurrence(ArrayList<Integer> ar) {
        int res = 0;
        for (int i = 0; i < ar.size(); i++)
            res ^= ar.get(i);

        return res;
    }

    public static void main(String[] args) {
        ArrayList<Integer> ar = 
        new ArrayList<>(Arrays.asList
           (2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2));

        // Function calling
        System.out.println(getOddOccurrence(ar));
    }
}
Python
    
# Python program to find the element occurring odd number of times

def getOddOccurrence(arr):

    # Initialize result
    res = 0
    
    # Traverse the array
    for element in arr:
        # XOR with the result
        res = res ^ element

    return res

# Test array
arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]

print("%d" % getOddOccurrence(arr))
C#
using System;
using System.Collections.Generic;

class GFG
{
    // Function to find element occurring odd number of times
    static int GetOddOccurrence(List<int> ar)
    {
        int res = 0;
        for (int i = 0; i < ar.Count; i++)
            res ^= ar[i];

        return res;
    }

    static void Main()
    {
        List<int> ar = new List<int> { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };

        // Function calling
        Console.WriteLine(GetOddOccurrence(ar));
    }
}
JavaScript
function getOddOccurrence(arr) {
    let res = 0;

    for (let i = 0; i < arr.length; i++) {
        res ^= arr[i];
    }

    return res;
}

// Driver code
let arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2];
console.log(getOddOccurrence(arr));
PHP
<?php

// Function to find element 
// occurring odd number of times
function getOddOccurrence(&$ar, $ar_size)
{
    $res = 0; 
    for ($i = 0; $i < $ar_size; $i++)     
        $res = $res ^ $ar[$i];
    
    return $res;
}

// Driver Code
$ar = array(2, 3, 5, 4, 5, 2,
            4, 3, 5, 2, 4, 4, 2);
$n = sizeof($ar);

// Function calling
echo(getOddOccurrence($ar, $n));

?>

Output
5

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


Exceptionally odd | DSA Problem

Explore