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:


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:


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:

Output:

Element appear only once in array – 4

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: