Given an array where every element appears twice except a pair (two elements). Find the elements of this unique pair.
Input : 6, 1, 3, 5, 1, 3, 7, 6 Output : 5 7 All elements appear twice except 5 and 7 Input : 1 3 4 1 Output : 3 4
The idea is based on below post.
1. XOR each element of the array and you will left with the XOR of two different elements which are going to be our result. Let this XOR be “XOR”
2. Now find a set bit in XOR.
3. Now divide array elements in two groups. One group that has the bit found in step 2 as set and other group that has the bit as 0.
4. XOR of elements present in first group would be our first element. And XOR of elements present in second group would be our second element.
The unique pair is (7, 5)
This article is contributed by Dhiman Mayank. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of unique pairs in an array
- Sort an array of pairs using Java Pair and Comparator
- Find the maximum cost of an array of pairs choosing at most K pairs
- Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Find Sum of all unique sub-array sum for a given array.
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Find a pair (n,r) in an integer array such that value of nCr is maximum
- Find pair with greatest product in array
- Find a pair (n,r) in an integer array such that value of nPr is maximum
- All pairs whose xor gives unique prime
- Count of unique pairs (arr[i], arr[j]) such that i < j
- Find a pair with maximum product in array of Integers
- Given an absolute sorted array and a number K, find the pair whose sum is K
- Find pairs in array whose sums already exist in array