DEV Community

Cover image for Find out first unique element from array
Indrakant Mishra
Indrakant Mishra

Posted on

Find out first unique element from array

Hello..., let's find how how we can find the unique element from an array from an unsorted array which has duplicate values -

let's initialize an array -

let a = [1,2,2,3,4,1,5,6,6,7]
Enter fullscreen mode Exit fullscreen mode

and create a variable and initialize it with a[0] value -

let r = a[0]
Enter fullscreen mode Exit fullscreen mode

now the main part, to iterate through array and find out the element with no duplicate value without creating any data structure and in single for loop -

for(let i=0; i<a.length; i++){
    r = r ^ a[i] 
    // here ^ is a bitwise XOR operator which gives a unique value. Here is how it works - if a value is same it gives 0 to it and if its a unique it returns 1 and for the value which is unique we get 1 and this is how we can find out unique element
}
Enter fullscreen mode Exit fullscreen mode

here is the complete code at one -

let a = [1,2,2,3,4,1,5,6,6,7]
let r = a[0]
for(let i=0; i<a.length; i++){
    r = r ^ a[i]
}
Enter fullscreen mode Exit fullscreen mode

Hope it helped you and you found it valuable.

Top comments (2)

Collapse
 
wraith profile image
Jake Lundberg

Love that you're sharing with the community! This unfortunately doesn't work though.

Here are a couple of example arrays that cause issues

This array will return 3 which is the last unique number.
let a = [1, 3, 2, 2];

This array will return 2 which is not unique;
let a = [1, 3, 1, 2, 2];

What do you think might be causing this?

Collapse
 
dr_anks profile image
An Architect

This solution is not full proof working for finding the correct unique. Sometime this can give you a number out from your array.
Try out for : [1,2,2,7,1] and let me know the result.