Elements that occurred only once in the array

20 May, 2021
Given an array arr that has numbers appearing twice or once. The task is to identify numbers that occur only once in the array. 
Note: Duplicates appear side by side every time. There might be a few numbers that can occur at one time and just assume this is a right rotating array (just say an array can rotate k times towards right). The order of the elements in the output doesn’t matter.
Examples: 
Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }
Output: 9 4

Input: arr[] = {-9, -8, 4, 4, 5, 5, -1}
Output: -9 -8 -1
Method-1: Using Sorting. 
Sort the array.
Check for each element at index i (except the first and last element), if
arr[i] != arr[i-1] && arr [i] != arr[i+1]
For the first element, check if arr[0] != arr[1].
For the last element, check if arr[n-1] != arr[n-2].
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){    // Sort the array    sort(arr, arr + n);     // Check for first element    if (arr[0] != arr[1])        cout << arr[0] << " ";     // Check for all the elements if it is different    // its adjacent elements    for (int i = 1; i < n - 1; i++)        if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1])            cout << arr[i] << " ";     // Check for the last element    if (arr[n - 2] != arr[n - 1])        cout << arr[n - 1] << " ";} // Driver codeint main(){     int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };    int n = sizeof(arr) / sizeof(arr[0]);     occurredOnce(arr, n);     return 0;}
// Java implementation// of above approachimport java.util.*; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){    // Sort the array    Arrays.sort(arr);     // Check for first element    if (arr[0] != arr[1])        System.out.println(arr[0] + " ");     // Check for all the elements    // if it is different    // its adjacent elements    for (int i = 1; i < n - 1; i++)        if (arr[i] != arr[i + 1] &&            arr[i] != arr[i - 1])            System.out.print(arr[i] + " ");     // Check for the last element    if (arr[n - 2] != arr[n - 1])        System.out.print(arr[n - 1] + " ");} // Driver codepublic static void main(String args[]){    int arr[] = {7, 7, 8, 8, 9,                 1, 1, 4, 2, 2};    int n = arr.length;     occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu
# Python 3 implementation# of above approach # Function to find the elements# that appeared only once in# the arraydef occurredOnce(arr, n):         # Sort the array    arr.sort()     # Check for first element    if arr[0] != arr[1]:        print(arr[0], end = " ")     # Check for all the elements    # if it is different its    # adjacent elements    for i in range(1, n - 1):        if (arr[i] != arr[i + 1] and            arr[i] != arr[i - 1]):            print( arr[i], end = " ")     # Check for the last element    if arr[n - 2] != arr[n - 1]:        print(arr[n - 1], end = " ") # Driver codeif __name__ == "__main__":     arr = [ 7, 7, 8, 8, 9,            1, 1, 4, 2, 2 ]    n = len(arr)    occurredOnce(arr, n) # This code is contributed# by ChitraNayal
// C# implementation// of above approachusing System; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){    // Sort the array    Array.Sort(arr);     // Check for first element    if (arr[0] != arr[1])        Console.Write(arr[0] + " ");     // Check for all the elements    // if it is different    // its adjacent elements    for (int i = 1; i < n - 1; i++)        if (arr[i] != arr[i + 1] &&            arr[i] != arr[i - 1])            Console.Write(arr[i] + " ");     // Check for the last element    if (arr[n - 2] != arr[n - 1])        Console.Write(arr[n - 1] + " ");} // Driver codepublic static void Main(){    int[] arr = {7, 7, 8, 8, 9,                1, 1, 4, 2, 2};    int n = arr.Length;     occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal
<?php// PHP implementation// of above approach // Function to find the elements// that appeared only once in// the arrayfunction occurredOnce(&$arr, $n){    // Sort the array    sort($arr);     // Check for first element    if ($arr[0] != $arr[1])        echo $arr[0]." ";     // Check for all the elements    // if it is different its    // adjacent elements    for ($i = 1; $i < $n - 1; $i++)        if ($arr[$i] != $arr[$i + 1] &&            $arr[$i] != $arr[$i - 1])            echo $arr[$i]." ";     // Check for the last element    if ($arr[$n - 2] != $arr[$n - 1])        echo $arr[$n - 1]." ";} // Driver code$arr = array(7, 7, 8, 8, 9,             1, 1, 4, 2, 2);$n = sizeof($arr);occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript implementation// of above approach // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr,n){    // Sort the array    arr.sort(function(a,b){return a-b;});      // Check for first element    if (arr[0] != arr[1])        document.write(arr[0] + " ");      // Check for all the elements    // if it is different    // its adjacent elements    for (let i = 1; i < n - 1; i++)        if (arr[i] != arr[i + 1] &&            arr[i] != arr[i - 1])            document.write(arr[i] + " ");      // Check for the last element    if (arr[n - 2] != arr[n - 1])        document.write(arr[n - 1] + " ");} // Driver codelet arr=[7, 7, 8, 8, 9,                 1, 1, 4, 2, 2];let n = arr.length;occurredOnce(arr, n);  // This code is contributed by rag2127 </script>
4 9 
Time Complexity: O(Nlogn) Space Complexity: O(1)
Method-2: (Using Hashing): In C++, unordered_map can be used for hashing. 
Traverse the array.
Store each element with its occurrence in the unordered_map.
Traverse the unordered_map and print all the elements with occurrence 1.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){    unordered_map<int, int> mp;     // Store all the elements in the map with    // their occurrence    for (int i = 0; i < n; i++)        mp[arr[i]]++;     // Traverse the map and print all the    // elements with occurrence 1    for (auto it = mp.begin(); it != mp.end(); it++)        if (it->second == 1)            cout << it->first << " ";} // Driver codeint main(){     int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };    int n = sizeof(arr) / sizeof(arr[0]);     occurredOnce(arr, n);     return 0;}
// Java implementation to find elements// that appeared only onceimport java.util.*;import java.io.*; class GFG{    // Function to find the elements that    // appeared only once in the array    static void occurredOnce(int[] arr, int n)    {            HashMap<Integer, Integer> mp = new HashMap<>();                         // Store all the elements in the map with            // their occurrence            for (int i = 0; i < n; i++)            {                if (mp.containsKey(arr[i]))                    mp.put(arr[i], 1 + mp.get(arr[i]));                else                    mp.put(arr[i], 1);            }             // Traverse the map and print all the            // elements with occurrence 1            for (Map.Entry entry : mp.entrySet())            {                if (Integer.parseInt(String.valueOf(entry.getValue())) == 1)                    System.out.print(entry.getKey() + " ");            }    }     // Driver code    public static void main(String args[])    {            int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };            int n = arr.length;             occurredOnce(arr, n);    }} // This code is contributed by rachana soma
# Python3 implementation to find elements# that appeared only onceimport math as mt # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n):     mp = dict()     # Store all the elements in the    # map with their occurrence    for i in range(n):        if arr[i] in mp.keys():            mp[arr[i]] += 1        else:            mp[arr[i]] = 1     # Traverse the map and print all    # the elements with occurrence 1    for it in mp:        if mp[it] == 1:            print(it, end = " ") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by# Mohit Kumar 29
// C# implementation to find elements// that appeared only onceusing System;using System.Collections.Generic;class GFG{    // Function to find the elements that    // appeared only once in the array    static void occurredOnce(int[] arr, int n)    {      Dictionary<int, int> mp = new Dictionary<int, int>();       // Store all the elements in the map with      // their occurrence      for (int i = 0; i < n; i++)      {        if (mp.ContainsKey(arr[i]))          mp[arr[i]] = 1 + mp[arr[i]];        else          mp.Add(arr[i], 1);      }       // Traverse the map and print all the      // elements with occurrence 1      foreach(KeyValuePair<int, int> entry in mp)      {        if (Int32.Parse(String.Join("", entry.Value)) == 1)          Console.Write(entry.Key + " ");      }    }     // Driver code    public static void Main(String []args)    {      int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };      int n = arr.Length;      occurredOnce(arr, n);    }} // This code is contributed by shikhasingrajput
<script> // Javascript implementation to find elements// that appeared only once     // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){    let mp = new Map();         // Store all the elements in the map    // with their occurrence    for(let i = 0; i < n; i++)    {        if (mp.has(arr[i]))            mp.set(arr[i], 1 + mp.get(arr[i]));        else            mp.set(arr[i], 1);    }     // Traverse the map and print all the    // elements with occurrence 1    for(let [key, value] of mp.entries())    {        if (value == 1)            document.write(key + " ");    }} // Driver codelet arr = [ 7, 7, 8, 8, 9,            1, 1, 4, 2, 2 ];let n = arr.length; occurredOnce(arr, n); // This code is contributed by avanitrachhadiya2155 </script>
4 9 
Time Complexity: O(N) Space Complexity: O(N)
Method-3: Using given assumptions. It is given that an array can be rotated any time and duplicates will appear side by side every time. So, after rotating, the first and last elements will appear side by side. 
Check if the first and last elements are equal. If yes, then start traversing the elements between them.
Check if the current element is equal to the element in the immediate previous index. If yes, check the same for the next element.
If not, print the current element.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){    int i = 1, len = n;     // Check if the first and last element is equal    // If yes, remove those elements    if (arr[0] == arr[len - 1]) {        i = 2;        len--;    }     // Start traversing the remaining elements    for (; i < n; i++)         // Check if current element is equal to        // the element at immediate previous index        // If yes, check the same for next element        if (arr[i] == arr[i - 1])            i++;         // Else print the current element        else            cout << arr[i - 1] << " ";     // Check for the last element    if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2])        cout << arr[n - 1];} // Driver codeint main(){     int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };    int n = sizeof(arr) / sizeof(arr[0]);     occurredOnce(arr, n);     return 0;}
// Java implementation to find// elements that appeared only onceclass GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){    int i = 1, len = n;     // Check if the first and last    // element is equal. If yes,    // remove those elements    if (arr[0] == arr[len - 1])    {        i = 2;        len--;    }     // Start traversing the    // remaining elements    for (; i < n; i++)         // Check if current element is        // equal to the element at        // immediate previous index        // If yes, check the same        // for next element        if (arr[i] == arr[i - 1])            i++;         // Else print the current element        else            System.out.print(arr[i - 1] + " ");     // Check for the last element    if (arr[n - 1] != arr[0] &&        arr[n - 1] != arr[n - 2])        System.out.print(arr[n - 1]);} // Driver codepublic static void main(String args[]){    int arr[] = {7, 7, 8, 8, 9,                 1, 1, 4, 2, 2};    int n = arr.length;     occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu
# Python 3 implementation to find# elements that appeared only once # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n):    i = 1    len = n     # Check if the first and    # last element is equal    # If yes, remove those elements    if arr[0] == arr[len - 1]:        i = 2        len -= 1     # Start traversing the    # remaining elements    while i < n:         # Check if current element is        # equal to the element at        # immediate previous index        # If yes, check the same for        # next element        if arr[i] == arr[i - 1]:            i += 1         # Else print the current element        else:            print(arr[i - 1], end = " ")                     i += 1     # Check for the last element    if (arr[n - 1] != arr[0] and        arr[n - 1] != arr[n - 2]):        print(arr[n - 1]) # Driver codeif __name__ == "__main__":    arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ]    n = len(arr)     occurredOnce(arr, n) # This code is contributed# by ChitraNayal
// C# implementation to find// elements that appeared only onceusing System; class GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){    int i = 1, len = n;     // Check if the first and last    // element is equal. If yes,    // remove those elements    if (arr[0] == arr[len - 1])    {        i = 2;        len--;    }     // Start traversing the    // remaining elements    for (; i < n; i++)         // Check if current element is        // equal to the element at        // immediate previous index        // If yes, check the same        // for next element        if (arr[i] == arr[i - 1])            i++;         // Else print the current element        else            Console.Write(arr[i - 1] + " ");     // Check for the last element    if (arr[n - 1] != arr[0] &&        arr[n - 1] != arr[n - 2])        Console.Write(arr[n - 1]);} // Driver codepublic static void Main(){    int[] arr = {7, 7, 8, 8, 9,                1, 1, 4, 2, 2};    int n = arr.Length;     occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal
<?php// PHP implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(&$arr, $n){    $i = 1;    $len = $n;     // Check if the first and last    // element is equal. If yes,    // remove those elements    if ($arr[0] == $arr[$len - 1])    {        $i = 2;        $len--;    }     // Start traversing the    // remaining elements    for (; $i < $n; $i++)         // Check if current element is        // equal to the element at        // immediate previous index        // If yes, check the same for        // next element        if ($arr[$i] == $arr[$i - 1])            $i++;         // Else print the current element        else            echo $arr[$i - 1] . " ";     // Check for the last element    if ($arr[$n - 1] != $arr[0] &&        $arr[$n - 1] != $arr[$n - 2])        echo $arr[$n - 1];} // Driver code$arr = array(7, 7, 8, 8, 9,             1, 1, 4, 2, 2);$n = sizeof($arr); occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){    var i = 1, len = n;     // Check if the first and last    // element is equal. If yes,    // remove those elements    if (arr[0] == arr[len - 1])    {        i = 2;        len--;    }     // Start traversing the    // remaining elements    for(; i < n; i++)         // Check if current element is        // equal to the element at        // immediate previous index        // If yes, check the same        // for next element        if (arr[i] == arr[i - 1])            i++;         // Else print the current element        else            document.write(arr[i - 1] + " ");     // Check for the last element    if (arr[n - 1] != arr[0] &&        arr[n - 1] != arr[n - 2])        document.write(arr[n - 1]);} // Driver codevar arr = [ 7, 7, 8, 8, 9,            1, 1, 4, 2, 2 ];var n = arr.length; occurredOnce(arr, n); // This code is contributed by Ankita saini </script>
9 4 
Time Complexity: O(N) Space Complexity: O(1)
Count the frequencies of every element using the Counter function
Traverse the frequency array and print all the elements with occurrence 1.
Below is the implementation
Python3
# Python3 implementation to find elements# that appeared only oncefrom collections import Counter # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n):     #counting frequency of every element using Counter    mp=Counter(arr)    # Traverse the map and print all    # the elements with occurrence 1    for it in mp:        if mp[it] == 1:            print(it, end = " ") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by vikkycirus
9 4 
Time Complexity: O(n)
andrew1234
ukasp
SivaPrakashReddyKomma
mohit kumar 29
rachana soma
shikhasingrajput
vikkycirus
rag2127
avanitrachhadiya2155
ankita_saini
Amazon
cpp-unordered_map
Picked
rotation
Arrays
Hash
Sorting
Amazon
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Next Greater Element
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence