Priyath Gregory
Priyath Gregory

Reputation: 987

odd one out algorithm

given a set of N numbers, i am supposed to find the odd one out. now N is an odd number, and the way to determine the 'odd one out' is by pairing the given numbers together, and eventually you'll be left with one number, which is the 'odd one out' .

The numbers are paired according to the distance between them. So first, two numbers with the least distance between them are picked from the given set of numbers and paired together. This leaves us with N-2 numbers in the set. The process is repeated until there is only 1 number left.

example: {1,4,3}

the distance between 1 and 3 is 2 and the distance between 3 and 4 is just 1. So 3 and 4 are paired which leaves us with 1 unpaired making it the odd man.

So far all i could think of is to sort the given list, and find the difference between each of the numbers and eliminate pairs, starting with the pair with the least distance between them. This would eventually land me with the 'odd one out' but the problem has to be solved with an algorithm that has a complexity less than O(N^2). Some help in the right direction would be greatly appreciated. Thank you

one more example: {1,3,4,6,10}

pair with least difference 3,4 eliminate pair -> {1,6,10} pair with least difference 6,10 eliminate pair -> {1} is the odd one out

another example {2,4,1,10,8,9,6}

pair with least difference (1,2) (8,9) and (9,10). eliminate (1,2) and (8,9) or (10,9) doesn't matter (for similar distances result can go either way; unpredictable) lets pick (8,9) -> {4,10,6}

next eliminate (4,6) --> {10} is the odd one out note: could have picked (9,10) instead of (8,9) as well.

i hope this clears up things

Upvotes: 4

Views: 6709

Answers (1)

Abhishek Bansal
Abhishek Bansal

Reputation: 12705

One possible O(nlogn) solution is as follows:

  1. Sort the array (in O(nlogn) time).
  2. Compute the differences between adjacent elements in the sorted array.
  3. Store the difference values (along with the respective pairs) in a min-heap.
  4. Pop out the top pair from the min-heap. For every popped out pair, you will have to add another pair to the heap. This will be corresponding to the adjacent elements from the popped out pair. For example if the array was {...., 3, 5, 6, 9, ....} and the popped out pair was {5,6}, then add another pair in the heap {3,9} with a difference value of 6.
  5. Also, keep track of the elements already popped out (probably in a hash table) and simply reject any popped pair for which any of the elements is already popped out.
  6. Once the heap is empty, the element that was not included in any valid popped out pair shall be the odd one out.

Upvotes: 3

Related Questions