Saturday, April 24, 2010

Removing duplicates in an array of n elements:

Question: You are given an array of n elements, and you notice that some of the elements are duplicates; that is, they appear more than once in an array. Show how to remove all the duplicates from the array in time O(n log n).


Answer:
If you remember the algorithm for mergesort, you should be able to solve this problem. While merging the subarrays and comparing elements, add an extra condition which is "if the elements are equal, remove one of them." Done!


Possible Solution Code(in Python):


The above code outputs an array [1, 2, 3, 4, 5, 8, 9, 10, 14]. Good Luck!

No comments:

Post a Comment