# Find the only element in array which appears only once

Objec­tive: Given an array of integers, all the elements are appear twice but one element which appears only once. Write an algorithm to find that element.

Example:

```int [] a = { 1,5,6,2,1,6,4,3,2,5,3};
output: 4
```

Approach:

Brute Force:

Use nested loops and compare each element in array with all other elements and track the element which is non-repeated.

Time Complexity: O(n^2)

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 public class EveryElementsRepeatedButOne { public static void findBruteForce(int [] a){ boolean [] visited = new boolean[a.length]; for (int i = 0; i

Use Hashing:

·      Store the count of each element in a hash map.

·      Iterate through hash map and return the element which has count 1.

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

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class EveryElementsRepeatedButOne { public static void findByHashing(int [] a){ HashMap map = new HashMap(); for (int i = 0; i set = map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()){ int key = iterator.next(); if(map.get(key)==1){ System.out.println("Element appear only once in array – " + key); } } } public static void main(String[] args) { int [] a = { 1,5,6,2,1,6,4,3,2,5,3}; findByHashing(a); } }

Use XOR

·      We know that A XOR A = 0.

·      If we XOR all the elements in array, all the elements which are repeated twice will become 0 and remaining will the element which is appearing only once.

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
`Element appear only once in array – 4`