Alex Rivera | Logout

Find the one non-repeating element in array?

Asked 2012-04-20T04:56:02.133
10

I have an array of n elements in which only one element is not repeated, else all the other numbers are repeated >1 times. And there is no limit on the range of the numbers in the array.

Some solutions are:

  • Making use of hash, but that would result in linear time complexity but very poor space complexity
  • Sorting the list using MergeSort O(nlogn) and then finding the element which doesn't repeat

Is there a better solution?

Edit
Report

1 Answer

1

One general approach is to implement a bucketing technique (of which hashing is such a technique) to distribute the elements into different "buckets" using their identity (say index) and then find the bucket with the smallest size (1 in your case). This problem, I believe, is also known as the minority element problem. There will be as many buckets as there are unique elements in your set.

Doing this by hashing is problematic because of collisions and how your algorithm might handle that. Certain associative array approaches such as tries and extendable hashing don't seem to apply as they are better suited to strings.

One application of the above is to the Union-Find data structure. Your sets will be the buckets and you'll need to call MakeSet() and Find() for each element in your array for a cost of $O(\alpha(n))$ per call, where $\alpha(n)$ is the extremely slow-growing inverse Ackermann function. You can think of it as being effectively a constant.

You'll have to do Union when an element already exist. With some changes to keep track of the set with minimum cardinality, this solution should work. The time complexity of this solution is $O(n\alpha(n))$.

Your problem also appears to be loosely related to the Element Uniqueness problem.

answered 2012-04-20T17:53:40.977

Your Answer