-3

Could someone help with writing an efficient java function for the below please?

Without using internal sorting or deduplication function, take an array which contains duplicate entries and return a new array without duplicates. eg

deduplicate(array(2,5,10,1, “john" “andy", 5, “peter”, “andy”)) 

// returns 2,5,10,1,“john”, “andy”, “peter”

jmj
  • 237,923
  • 42
  • 401
  • 438

1 Answers1

0

Start with a hash based container such as a HashMap and for each element in the array first check if it is present in the container and if not add it. When done return all the elements in the container as an array.

This will be efficient because each check to see if an element is in the container is O(1) and each insertion is O(1). Doing this for each element in the array is O(n) and then retrieving them again at the end is also O(n), so you end up with a solution that is O(n).

I leave the actual implementation up to you as an exercise.

mclaassen
  • 5,018
  • 4
  • 30
  • 52
  • A (Linked)HashSet would be more appropriate. And checking if it exists before adding it is useless, since a Set won't add an element that is already present. So it boils down to `new LinkedHashSet<>(Arrays.asList(array)).toArray()` – JB Nizet Jun 25 '14 at 20:17
  • @JBNizet I haven't done Java in a long time (I'm a C# guy). Not aware of the particular container types available. Internally I'm assuming that a (Linked)HashSet has to check if an item is present before adding it anyway. – mclaassen Jun 25 '14 at 20:21
  • 1
    Downvoted as it's useless to attempt to answer this question when OP isn't even able to correctly name the language he's supposed to program in - his example call definitely isn't java but might be javascript instead. Please don't attempt to guess what he could mean, wait for OP to clarify his question. I also doubt OP would be able to understand an answer like yours given his obvious lack of basic programming knowledge; the efficiency part probably went right over his head. – l4mpi Jun 25 '14 at 20:21
  • @l4mpi Fair enough. I wanted to give a general solution so that he could try it himself and maybe learn something while attempting it. – mclaassen Jun 25 '14 at 20:23