Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two.
Examples:
Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8}
Output : 2 7
Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50}
Output : 7 15
Simple solution :
Approach :
A simple solution is to use two nested loops. The outer loop traverses through all elements. The inner loop counts occurrences of the current element. We print the elements whose counts of occurrences are odd.
Below is the code of the given approach :
C++
// CPP code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <bits/stdc++.h>using namespace std;Â
void printOdds(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 += 1;            }        }        if (count % 2 != 0) {            cout << arr[i]                 << " "; // Print the elements that occur                         // odd number of times in an array        }    }    cout << endl;}Â
// Driver codeint main(){    int arr[] = { 2, 3, 3, 4, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    // function call    printOdds(arr, n);    return 0;}Â
// This code is contributed by Suruchi Kumari |
C
// C code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <stdio.h>Â
void printOdds(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 += 1;            }        }        if (count % 2 != 0) {            printf(                "%d ",                arr[i]); // Print the elements that occur                         // odd number of times in an array        }    }    printf("\n");}Â
// Driver codeint main(){    int arr[] = { 2, 3, 3, 4, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    // function call    printOdds(arr, n);    return 0;}Â
// This code is contributed by Suruchi Kumari |
Java
// Java program to find the maximum stolen valuepublic class GFG {Â
  // calculate the maximum stolen value  static void printOdds(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 += 1;        }      }      if (count % 2 != 0) {        System.out.print(arr[i]+" ");// Print the elements that occur        // odd number of times in an array      }    }    System.out.print("\n");  }Â
  // Driver Code  public static void main (String[] args)  {    int arr[] = { 2, 3, 3, 4, 4, 5 };    int n = arr.length;Â
    // function call    printOdds(arr, n);  }}// This code is contributed by adityapatil12 |
Python3
# python3 code for the above approachÂ
# Function to find and Replace in Stringdef printOdds(arr, n) :         for i in range(0,n) :        count = 0        for j in range(0,n) :            if arr[i] == arr[j] :                count += 1        if count % 2 != 0 :            print(arr[i],end=' ') # Print the elements that occur                                   # odd number of times in an array   # Driver codeif __name__ == "__main__" :         arr = [ 2, 3, 3, 4, 4, 5 ]    n = len(arr)         #Function call    printOdds(arr,n)Â
# This code is contributed by adityapatil12 |
C#
// Include namespace systemusing System;Â
// C# program to find the maximum stolen valuepublic class GFG{    // calculate the maximum stolen value    public static void printOdds(int[] arr, int n)    {        for (int i = 0; i < n; i++)        {            var count = 0;            for (int j = 0; j < n; j++)            {                if (arr[i] == arr[j])                {                    count += 1;                }            }            if (count % 2 != 0)            {                Console.Write(arr[i].ToString() + " ");            }        }        Console.Write("\n");    }    // Driver Code    public static void Main(String[] args)    {        int[] arr = {2, 3, 3, 4, 4, 5};        var n = arr.Length;        // function call        GFG.printOdds(arr, n);    }}Â
// This code is contributed by aadityaburujwale. |
Javascript
// JavaScript code to find two odd occurring elements// in an array where all other elements appear// even number of times.function printOdds(arr, n){    for (var i = 0; i < n; i++) {        let count = 0;        for (var j = 0; j < n; j++) {            if (arr[i] == arr[j]) {                count += 1;            }        }        if (count % 2 != 0) {            process.stdout.write(arr[i] + " ");                        // Print the elements that occur                         // odd number of times in an array        }    }    process.stdout.write("\n");}Â
// Driver codelet arr = [ 2, 3, 3, 4, 4, 5 ];let n = arr.length;Â
// function callprintOdds(arr, n);Â
Â
// This code is contributed by phasing17 |
2 5
Complexity Analysis:
- Time complexity : O(n^2)
- Auxiliary space : O(n)
A better solution is to use hashing. Time complexity of this solution is O(n) but it requires extra space.
We can construct a frequency hashmap, then iterate over all of its key – value pairs, and print all keys whose values (frequency) are odd.
Implementation:
C++
// CPP code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <bits/stdc++.h>using namespace std;Â
Â
void printOdds(int arr[], int n){    //declaring an unordered map    unordered_map<int, int> freq;    //building the frequency table    for (int i = 0; i < n; i++)        freq[arr[i]]++;         //iterating over the map    for (auto& it: freq) {        //if the frequency is odd        //print the element        if (it.second % 2)            cout << it.first << " ";    }}Â
// Driver codeint main(){    int arr[] = { 2, 3, 3, 4, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    //function call    printOdds(arr, n);    return 0;}Â
//this code is contributed by phasing17 |
Java
/*package whatever //do not write package name here */import java.util.*;Â
class GFG {    static void printOdds(int arr[], int n)    {        // declaring an unordered map        TreeMap<Integer, Integer> freq = new TreeMap<>(Collections.reverseOrder());               // building the frequency table        for (int i = 0; i < n; i++) {            freq.put(arr[i],                     freq.getOrDefault(arr[i], 0) + 1);        }Â
        // iterating over the map        for (int i : freq.keySet()) {            // if the frequency is odd            // print the element            if (freq.get(i) % 2 == 1)                System.out.print(i + " ");        }    }    public static void main(String[] args)    {        int arr[] = { 2, 3, 3, 4, 4, 5 };        int n = arr.length;               // function call        printOdds(arr, n);    }}Â
// This code is contributed by aadityaburujwale. |
Python3
# Python code to find two odd occurring elements# in an array where all other elements appear# even number of times.from collections import defaultdictÂ
def printOdds(arr, n):    freq = defaultdict(int)         # building the frequency table    for i in range(n):        freq[arr[i]] += 1             # iterating over the map    for key, value in freq.items():               # if the frequency is odd        # print the element        if value % 2:            print(key,end=" ")Â
# Driver codearr = [2, 3, 3, 4, 4, 5]n = len(arr)Â
# function callprintOdds(arr, n)Â
# this code is contributed by akashish__ |
C#
// C# code to find two odd occurring elements// in an array where all other elements appear// even number of times.using System;using System.Collections.Generic;Â
public class GFG {  static void printOdds(int[] arr, int n)  {         // declaring an unordered map    Dictionary<int, int> freq      = new Dictionary<int, int>();         // building the frequency table    for (int i = 0; i < n; i++) {      if (freq.ContainsKey(arr[i])) {        int val = freq[arr[i]];        freq.Remove(arr[i]);        freq.Add(arr[i], val + 1);      }      else {        freq.Add(arr[i], 1);      }    }Â
    // iterating over the map    foreach(KeyValuePair<int, int> entry in freq)    {             // if the frequency is odd      // print the element      if (entry.Value % 2 != 0)        Console.Write(entry.Key + " ");    }  }Â
  // Driver code  static public void Main()  {    int[] arr = { 2, 3, 3, 4, 4, 5 };    int n = 6;         // function call    printOdds(arr, n);  }}Â
// This code is contributed by garg28harsh. |
Javascript
// function code to find two odd occurring elements// in an array where all other elements appear// even number of times.function printOdds(arr, n){    // declaring an unordered map    var mp = new Map();         // building the frequency table    for (var i = 0; i < n; i++)    {        if(mp.has(arr[i]))            mp.set(arr[i], mp.get(arr[i])+1);        else            mp.set(arr[i], 1);    }    let el=[];    mp.forEach(( key,value) => {        if(key%2!=0)        {            el.push(value);        }    });     console.log(el);}Â
// Driver codeÂ
    let arr = [2, 3, 3, 4, 4, 5 ];    let n = arr.length;         // function call    printOdds(arr, n);Â
// This code is contributed by garg28harsh. |
5 2
Complexity Analysis:
- Time Complexity: O(n)
- Space Complexity: O(n)
An efficient solution is to use bitwise operators. The idea is based on approach used in two missing elements and two repeating elements. Â
Implementation:
C++
// CPP code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <bits/stdc++.h>using namespace std;Â
void printOdds(int arr[], int n){    // Find XOR of all numbers    int res = 0;    for (int i = 0; i < n; i++)        res = res ^ arr[i];Â
    // Find a set bit in the XOR (We find    // rightmost set bit here)    int set_bit = res & (~(res - 1));Â
    // Traverse through all numbers and    // divide them in two groups     // (i) Having set bit set at same     //    position as the only set bit     //    in set_bit    // (ii) Having 0 bit at same position    //     as the only set bit in set_bit    int x = 0, y = 0;    for (int i = 0; i < n; i++) {        if (arr[i] & set_bit)            x = x ^ arr[i];        else            y = y ^ arr[i];    }Â
    // XOR of two different sets are our    // required numbers.    cout << x << " " << y;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 2, 3, 3, 4, 4, 5 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â printOdds(arr, n);Â Â Â Â return 0;} |
Java
// Java code to find two // odd occurring elements// in an array where all// other elements appear// even number of times.Â
class GFG{static void printOdds(int arr[],                       int n){    // Find XOR of    // all numbers    int res = 0;    for (int i = 0; i < n; i++)        res = res ^ arr[i];Â
    // Find a set bit in the     // XOR (We find rightmost     // set bit here)    int set_bit = res &                   (~(res - 1));Â
    // Traverse through all     // numbers and divide them     // in two groups (i) Having     // set bit set at same position     // as the only set bit in     // set_bit (ii) Having 0 bit at    // same position as the only     // set bit in set_bit    int x = 0, y = 0;    for (int i = 0; i < n; i++)    {        if ((arr[i] & set_bit) != 0)            x = x ^ arr[i];        else            y = y ^ arr[i];    }Â
    // XOR of two different     // sets are our required    // numbers.    System.out.println( x + " " + y);}Â
// Driver codepublic static void main(String [] args){Â Â Â Â int arr[] = { 2, 3, 3, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 4, 4, 5 };Â Â Â Â int n = arr.length;Â Â Â Â printOdds(arr, n);}}Â
// This code is contributed by// Smitha Dinesh Semwal |
Python3
# Python 3 code to find two # odd occurring elements in# an array where all other # elements appear even number# of times.def printOdds(arr, n):Â
    # Find XOR of all numbers    res = 0    for i in range(0, n):        res = res ^ arr[i]Â
    # Find a set bit in     # the XOR (We find     # rightmost set bit here)    set_bit = res & (~(res - 1))Â
    # Traverse through all numbers     # and divide them in two groups     # (i) Having set bit set at     # same position as the only set     # bit in set_bit    # (ii) Having 0 bit at same     # position as the only set    # bit in set_bit    x = 0    y = 0    for i in range(0, n):        if (arr[i] & set_bit):            x = x ^ arr[i]        else:            y = y ^ arr[i]         # XOR of two different    # sets are our    # required numbers.    print(x , y, end = "")Â
# Driver codearr = [2, 3, 3, 4, 4, 5 ]n = len(arr) printOdds(arr, n)Â
# This code is contributed# by Smitha |
C#
// C# code to find two // odd occurring elements// in an array where all// other elements appear// even number of times.using System;Â
class GFG{static void printOdds(int []arr,                       int n){    // Find XOR of    // all numbers    int res = 0;    for (int i = 0; i < n; i++)        res = res ^ arr[i];Â
    // Find a set bit in the     // XOR (We find rightmost     // set bit here)    int set_bit = res &                (~(res - 1));Â
    // Traverse through all     // numbers and divide them     // in two groups (i) Having     // set bit set at same position     // as the only set bit in     // set_bit (ii) Having 0 bit at    // same position as the only     // set bit in set_bit    int x = 0, y = 0;    for (int i = 0; i < n; i++)    {        if ((arr[i] & set_bit) != 0)            x = x ^ arr[i];        else            y = y ^ arr[i];    }Â
    // XOR of two different     // sets are our required    // numbers.    Console.WriteLine(x + " " + y);}Â
// Driver codepublic static void Main(){Â Â Â Â int []arr = { 2, 3, 3, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 4, 4, 5 };Â Â Â Â int n = arr.Length;Â Â Â Â printOdds(arr, n);}}Â
// This code is contributed by// Akanksha Rai(Abby_akku) |
PHP
<?php// PHP code to find two odd // occurring elements in an // array where all other elements // appear even number of times.function printOdds($arr, $n){    // Find XOR of all numbers    $res = 0;    for ($i = 0; $i < $n; $i++)        $res = $res ^ $arr[$i];Â
    // Find a set bit in the     // XOR (We find rightmost    // set bit here)    $set_bit = $res & (~($res - 1));Â
    // Traverse through all numbers    // and divide them in two groups     // (i) Having set bit set at same     // position as the only set bit     // in set_bit    // (ii) Having 0 bit at same position    // as the only set bit in set_bit    $x = 0;    $y = 0;    for ($i = 0; $i < $n; $i++)    {        if ($arr[$i] & $set_bit)            $x = $x ^ $arr[$i];        else            $y = $y ^ $arr[$i];    }Â
    // XOR of two different sets    // are our required numbers.    echo($x . " " . $y);}Â
// Driver code$arr = array( 2, 3, 3, 4, 4, 5 );$n = sizeof($arr);printOdds($arr, $n);Â
// This code is contributed by Smitha?> |
Javascript
<script>Â
// Javascript code to find two odd// occurring elements in an array// where all other elements appear// even number of times.function printOdds(arr, n){         // Find XOR of all numbers    let res = 0;    for(let i = 0; i < n; i++)        res = res ^ arr[i];Â
    // Find a set bit in the XOR (We find    // rightmost set bit here)    let set_bit = res & (~(res - 1));Â
    // Traverse through all numbers and    // divide them in two groups     // (i) Having set bit set at same     //    position as the only set bit     //    in set_bit    // (ii) Having 0 bit at same position    //     as the only set bit in set_bit    let x = 0, y = 0;    for(let i = 0; i < n; i++)     {        if (arr[i] & set_bit)            x = x ^ arr[i];        else            y = y ^ arr[i];    }Â
    // XOR of two different sets are our    // required numbers.    document.write(x + " " + y);}Â
// Driver codelet arr = [ 2, 3, 3, 4, 4, 5 ];let n = arr.length;Â
printOdds(arr, n);Â
// This code is contributed by subhammahato348Â
</script> |
5 2
Complexity Analysis:
- Time Complexity : O(n)Â
- Auxiliary Space : O(1)
Another Efficient Solution (Using binary search) : Sort the array for binary search . Then we can find frequency of all array elements using binary search function . Then we can check if frequency of array element is odd or not , If frequency is odd , then print that element .
Below is the implementation of above approach:
C++
// C++ implementation of the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find element that occurs // odd times in the array void printOdds(int arr[], int n){    int count = 0;   sort(arr,arr+n);//sort array for binary search       for(int i = 0 ; i < n ;i++)   {      //index of first and last occ of arr[i]     int first_index = lower_bound(arr,arr+n,arr[i])- arr;     int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;     i = last_index; // assign i to last_index to avoid printing                     // same element multiple time           int fre = last_index-first_index+1;//finding frequency     //( occurences of arr[i] in the array )           if(fre % 2 != 0)     { // if element occurs odd times then print that number          cout << arr[i]<<" ";                  }   } Â
}Â
// Drive codeint main(){     int arr[] = { 2, 3, 3, 4, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);       // Function call    printOdds(arr, n);    return 0;}Â
// This Code is contributed by nikhilsainiofficial546 |
Python3
# Function to find element that occurs# odd times in the arraydef printOdds(arr, n):    count = 0    arr.sort() # sort array for binary search    i = 0    while i < n:        # index of first and last occ of arr[i]        first_index = arr.index(arr[i])        last_index = len(arr) - arr[::-1].index(arr[i]) - 1        i = last_index # assign i to last_index to avoid printing        # same element multiple timeÂ
        fre = last_index - first_index + 1 # finding frequency        # (occurrences of arr[i] in the array)Â
        if fre % 2 != 0:            # if element occurs odd times then print that number            print(arr[i], end=' ')        i += 1Â
Â
# Drive codearr = [2, 3, 3, 4, 4, 5]n = len(arr)Â
# Function callprintOdds(arr, n) |
Javascript
// Function to find element that occurs odd times in the arrayfunction printOdds(arr, n) {    let count = 0;    arr.sort(); // sort array for binary search    let i = 0; let ans="";    while (i < n) {             // index of first and last occ of arr[i]        let first_index = arr.indexOf(arr[i]);        let last_index = arr.lastIndexOf(arr[i]);        i = last_index; // assign i to last_index to avoid printing same element multiple timesÂ
        let fre = last_index - first_index + 1; // finding frequency (occurrences of arr[i] in the array)           if (fre % 2 !== 0) {                     // if element occurs odd times then print that number            ans = ans + arr[i] + " ";        }         i += 1;    }console.log(ans);}Â
// Drive codelet arr = [2, 3, 3, 4, 4, 5];let n = arr.length;Â
// Function callprintOdds(arr, n); |
C#
// C# Equivalentusing System;Â
public class GFG {Â
    // Function to find element that occurs odd times in the    // array    static void printOdds(int[] arr, int n)    {        int count = 0;        Array.Sort(arr); // sort array for binary search        int i = 0;        string ans = "";        while (i < n) {Â
            // index of first and last occ of arr[i]            int first_index = Array.IndexOf(arr, arr[i]);            int last_index = Array.LastIndexOf(arr, arr[i]);            i = last_index; // assign i to last_index to                            // avoid printing same element                            // multiple timesÂ
            int fre = last_index - first_index                      + 1; // finding frequency (occurrences                           // of arr[i] in the array)Â
            if (fre % 2 != 0) {Â
                // if element occurs odd times then print                // that number                ans = ans + arr[i] + " ";            }            i += 1;        }        Console.WriteLine(ans);    }Â
    public static void Main()    {        // Driver's code        int[] arr = new int[] { 2, 3, 3, 4, 4, 5 };        int n = arr.Length;Â
        // Function call        printOdds(arr, n);    }} |
Java
import java.util.*;Â
class Main {    // Function to find element that occurs    // odd times in the array    static void printOdds(int[] arr, int n)    {        int count = 0;        Arrays.sort(arr); // sort array for binary searchÂ
        for (int i = 0; i < n; i++) {            // index of first and last occ of arr[i]            int first_index                = Arrays.binarySearch(arr, arr[i]);            int last_index = first_index;Â
            // handling case where element is not found by            // binary search            if (first_index < 0) {                continue;            }Â
            // loop to find last index of arr[i] in the            // array            while (last_index + 1 < n                   && arr[last_index + 1] == arr[i]) {                last_index++;            }            i = last_index; // assign i to last_index to                            // avoid printing same element                            // multiple timesÂ
            int fre = last_index - first_index                      + 1; // finding frequency                           // (occurrences of arr[i] in the                           // array)Â
            if (fre % 2 != 0) {                // if element occurs odd times then print                // that number                System.out.print(arr[i] + " ");            }        }    }Â
    // Drive code    public static void main(String[] args)    {        int[] arr = { 2, 3, 3, 4, 4, 5 };        int n = arr.length;Â
        // Function call        printOdds(arr, n); // Output: 2 5    }} |
2 5
Time Complexity: O(n*log2n), take log2n time for binary search functionÂ
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
