Find two non-repeating numbers in an array in O(n) time and O(1) space

Objective:  Given an array of integers which has all the repeating numbers (twice) but two numbers which are non-repeating. Write an algorithm to find out those two numbers.

Example

int [] arrA = {4,5,4,5,3,2,9,3,9,8};
Output: 2 and 8

Approaches:

This problem is similar to problem “Find two repeating elements in an array”. There could be multiple solutions like sort the array {O(nlogn)} or use hash map{Time complexity: O(n) , space complexity:  O(n)}

In this article we will discuss solution which has time complexity: O(n) and space complexity: O(1), constant extra space.

Use XOR: time complexity: O(n) and space complexity: O(1)

  • Let’s say non-repeating elements are X, Y.
  • A XOR A = 0
  • XOR all the elements of array. This will cancel all the repeated elements.
  • Result will be X XOR Y, since only X and Y are not repeating.
  • 1 XOR 1 =  0 and 1 XOR 0 = 1 with this logic in the result of X XOR Y if any kth bit is set to 1  implies either kth bit is 1 either in X or in Y not in both.
  • Use the above step to divide all the ele­ments in array into 2 groups, one group which has the ele­ments for which the kth bit is set to 1 and sec­ond group which has the ele­ments for which the kth bit is 0.
  • Let’s have that kth bit as right most set bit (Read how to find right most set bit)
  • Now we can claim that these two groups are respon­si­ble to pro­duce X and Y.
  • Group –1: XOR all the ele­ments whose kth bit is 1 will pro­duce either X or Y.
  • Group –2: XOR all the ele­ments whose kth bit is 0 will pro­duce either X or Y.
  • See the image below

 

Code:

Output:

Non Repeating Elements are: 2 and 8

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

  • Santanu Sahoo

    if the repetition is odd times, your logic fail then.
    try with input {2,3,1,3,2,7,3}

    • tutorialhorizon

      Thanks for pointing it out, will correct the objective of the question

%d bloggers like this: