I have an array where all the elements are repeated except one:
int[] a={2,6,6,2,4,1,4};
How can I find the element integer which is unpaired ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are a few approaches you can take:
i=0,i=2, etc.). Whena[i]anda[i+1]are unequal — or wheni+1 == a.length— you know thata[i]is unpaired.a[i], iterate over the elements (in a nested loop) and see if it ever occurs thata[i] == a[j]whilei != j. If not, thena[i]is unpaired.MINandMAX. Create anint[] b = new int[MAX-MIN+1]. Iterate over the elements again, incrementingb[a[i]-MIN]for each element. Then iterate overb; when you findb[j]==1,jis unpaired.Note: You use the term “element integer”, but that’s not a real term. The above assumes that you mean “integer-valued element”. If you actually mean “element index“, then only Approach 2 can be used without modification. Approach 3 would require a little bit of adjustment, and Approach 1 would require a lot of adjustment. (Of course, once you’ve found the value that occurs only once, you can just iterate over the array one more time to find the index of that value — provided you still have the original array order.)
Edited to add: I don’t know how I missed this before — I guess I’m not used to thinking of bitwise operations when writing Java — but the best solution is actually:
Approach 4 — O(n): compute the bitwise-XOR,
^, of all the elements of the array. This is the unpaired element. You see, XOR is commutative and associative, so2^6^6^2^4^1^4is the same as1^(2^2)^(4^4)^(6^6); andx^xis always0, so the pairs always cancel either other out. You can just write:to compute the unpaired element. (To get the index of the unpaired element, you’d then iterate over the array again, looking for
result.)