My algorithm for removing a duplicate from a list is not removing all duplicates

Viewed 54

The code only removes duplicates apart from the last 2 of any number

for (int i = 0; i < primeNumbers.Count; i = i + 1)
{
   for (int j = i + 1; j < primeNumbers.Count; j = j + 1)
   {
      if (primeNumbers[i] == primeNumbers[j])
      {
          primeNumbers.RemoveAt(j); 
         

      }
   }
}

for (int i = 0; i < primeNumbers.Count; i++)
    Console.WriteLine(primeNumbers[i]);
4 Answers

To improve time complexity, use a Set. A Set cannot have duplicates. Just iterate once through your list, and add each value to the set.

Complexity will be linear O(n).

this is simple and elegant:

const noDupes = primeNumbers.filter((item, ind, arr) => ind === arr.indexOf(item));

HTH

Your inner for loop will skip the next entry after the remove. After the remove, decrement j so that it will recheck the current entry on the next loop.

So add j--;

I would use the following code to improve:

If your primeNumbers is an Array[]:

primeNumbers = primeNumbers.Distinct().ToArray();

If your primeNumbers is an List<>:

primeNumbers = primeNumbers.Distinct().ToList();

If your primeNumbers is an HashSet<>:

primeNumbers = primeNumbers.Distinct().ToHashSet();

EXTRA When filling up your list of primenumbers, use HashSet

HashSet primeNumbers = new();
primeNumbers.Add(number);

It will automatically remove the duplicates.

This collection is introduced in . NET 3.5.

Related