Remove duplicate elements from an array (without?
LINQ Distinct())
Logic
- Use a HashSet to track seen elements.
- Add elements only if they are not already present.
int[] arr = { 1, 2, 3, 2, 4, 1 };
HashSet<int> set = new HashSet<int>();
List<int> result = new List<int>();
foreach (int num in arr)
{
if (!set.Contains(num))
{
set.Add(num);
result.Add(num);
}
}
Why this works:
HashSet ensures uniqueness with O(1) lookup.