VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-unique-pair-array-pairs-numbers/

⇱ Find Unique pair in an array with pairs of numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Unique pair in an array with pairs of numbers

Last Updated : 19 Jul, 2022

Given an array where every element appears twice except a pair (two elements). Find the elements of this unique pair.
Examples: 

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.
Find Two Missing Numbers | Set 2 (XOR based solution)

  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. 

Implementation:


Output
The unique pair is (7, 5)

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: