I have been working with a string[]
array in C# that gets returned from a function call. I could possibly cast to a Generic
collection, but I was wondering if there was a better way to do it, possibly by using a temp array.
What is the best way to remove duplicates from a C# array?
The following tested and working code will remove duplicates from an array. You must include the System.Collections namespace.
You could wrap this up into a function if you wanted to.
Simple solution:
Here is a O(n*n) approach that uses O(1) space.
The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.
Here is the HashSet<string> approach:
Unfortunately this solution also requires .NET framework 3.5 or later as HashSet was not added until that version. You could also use array.Distinct(), which is a feature of LINQ.
Maybe hashset which do not store duplicate elements and silently ignore requests to add duplicates.