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 email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- All pairs whose xor gives unique prime
- Find the maximum sum pair in an Array with even parity
- Unique element in an array where all elements occur k times except one
- Count of subarrays of an Array having all unique digits
- Find number of pairs in an array such that their XOR is 0
- Find the minimum value of the given expression over all pairs of the array
- Kth array element after M replacements of array elements by XOR of adjacent pairs
- Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
- Find pair for given sum in a sorted singly linked without extra space
- Find the number of pair of Ideal nodes in a given tree
- Maximum AND value of a pair in an array
- Print pair with maximum AND value in an array
- XOR of Sum of every possible pair of an array
- Quadruplet pair with XOR zero in the given Array
- Print all possible pair with prime XOR in the Array
- Maximum OR value of a pair in an Array | Set 2
- Maximum OR value of a pair in an Array without using OR operator
- Minimum XOR of OR and AND of any pair in the Array
- Count ordered pairs of positive numbers such that their sum is S and XOR is K
- Number of special pairs possible from the given two numbers