Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In a celebration of N individuals, every particular person is denoted by an integer. {Couples} are represented by the identical quantity. Discover out the one single particular person on the social gathering of {couples}.
Examples:
Enter: N = 5, arr = {1, 2, 3, 2, 1}
Output: 3
Explaination: Solely the quantity 3 is single.Enter: N = 11, arr = {1, 2, 3, 5, 3, 2, 1, 4, 5, 6, 6}
Output: 4
Explaination: 4 is the one single.
Naive method: To resolve the issue observe the beneath steps:
Illustration of the above method:
For e.g., we take an array of integers = {1, 1, 2, 3, 2, 3, 4, 5, 6, 5, 4}
After sorting the array turns into = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6}
As we are able to see, 6 is the only factor that doesn’t have its pair.
The time complexity of this algorithm can be O(N log N), as we’re sorting the array of numbers first which is the costliest operation.
To know the answer to this drawback, first, we’ve to know the Bitwise Operator, XOR. The reality desk of XOR is given beneath for reference:
To rapidly recap a very helpful property of XOR: When operated on two similar numbers, it returns 0. This property could be simply deduced by the reality desk given above. When a quantity can be XOR’ed with itself the binary illustration of each A and B within the above reality desk can be the identical and end in 0 in bits of all positions.
For Eg:
On the social gathering, we’ve two numbers which can be an identical to one another, which belong to the {couples}. If they’re XOR’ed with one another, they are going to return the reply as . To have a full understanding of the answer, we have to know that XOR is associative, i.e., the order of grouping doesn’t matter when a number of XOR operations are accomplished. For e.g.
So, if we XOR all of the numbers of attendees with one another, we’ll get hold of the quantity which doesn’t have its pair.
A pictorial illustration of the identical idea is given with the instance beneath:
Observe the steps to resolve the issue:
Under is the implementation for the above method:

Time complexity: O(N), the place N is the scale of the array as we’re traversing via the array as soon as.
Auxiliary House: O(1)