This is similar to Solution 2 by ridoy, except it preserves the original word order generating a new list for duplicate free result.
It is also
O(n) in time complexity. (Which isn't a big deal unless
st
gets
long!)
List<string> st = new List<string> { "Hello", "World", "Welcome", "To", "Csharp", "Welcome", "World", "Hello", "To", "Hello" };
HashSet<string> seen = new HashSet<string>();
List<string> duplicateFree = new List<string>();
List<int> deletedIndices = new List<int>();
int ix = 0;
foreach (var s in st)
{
if (seen.Add(s))
{
duplicateFree.Add(s);
}
else
{
deletedIndices.Add(ix);
}
++ix;
}
int[] deletedIndicesArray = deletedIndices.ToArray();