C# program to remove duplicates from array
HashSet to store unique elements and then converting it back to an array, like var unique = new HashSet(array).ToArray(); .Examples
How to Think About It
HashSet. Add each item from the array to this container, then get all unique items back as an array.Algorithm
Code
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] array = {1, 2, 2, 3, 4, 4, 5}; int[] unique = new HashSet<int>(array).ToArray(); Console.WriteLine("[{0}]", string.Join(", ", unique)); } }
Dry Run
Let's trace the example array [1, 2, 2, 3, 4, 4, 5] through the code.
Input array
array = [1, 2, 2, 3, 4, 4, 5]
Create HashSet
hashSet = {} (empty set)
Add elements to HashSet
Add 1 -> {1} Add 2 -> {1, 2} Add 2 (duplicate) ignored Add 3 -> {1, 2, 3} Add 4 -> {1, 2, 3, 4} Add 4 (duplicate) ignored Add 5 -> {1, 2, 3, 4, 5}
Convert HashSet to array
unique = [1, 2, 3, 4, 5]
Print result
Output: [1, 2, 3, 4, 5]
| Iteration | Element Added | HashSet Content |
|---|---|---|
| 1 | 1 | {1} |
| 2 | 2 | {1, 2} |
| 3 | 2 (ignored) | {1, 2} |
| 4 | 3 | {1, 2, 3} |
| 5 | 4 | {1, 2, 3, 4} |
| 6 | 4 (ignored) | {1, 2, 3, 4} |
| 7 | 5 | {1, 2, 3, 4, 5} |
Why This Works
Step 1: Using HashSet
A HashSet automatically stores only unique values, so adding duplicates has no effect.
Step 2: Adding elements
When you add each array element to the HashSet, duplicates are ignored silently.
Step 3: Converting back to array
After collecting unique elements, converting the HashSet back to an array gives the final result without duplicates.
Alternative Approaches
using System; using System.Linq; class Program { static void Main() { int[] array = {1, 2, 2, 3, 4, 4, 5}; int[] unique = array.Distinct().ToArray(); Console.WriteLine("[{0}]", string.Join(", ", unique)); } }
using System; using System.Collections.Generic; class Program { static void Main() { int[] array = {1, 2, 2, 3, 4, 4, 5}; List<int> uniqueList = new List<int>(); foreach (int num in array) { if (!uniqueList.Contains(num)) { uniqueList.Add(num); } } Console.WriteLine("[{0}]", string.Join(", ", uniqueList)); } }
Complexity: O(n) time, O(n) space
Time Complexity
Adding each element to a HashSet is O(1) on average, so total time is O(n) for n elements.
Space Complexity
Extra space is needed for the HashSet to store unique elements, which can be up to O(n).
Which Approach is Fastest?
Using HashSet or Distinct() is fastest and cleanest; manual loops with Contains are slower (O(n²)) for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| HashSet | O(n) | O(n) | Fast and efficient for all sizes |
| LINQ Distinct() | O(n) | O(n) | Clean and concise code |
| Manual loop with Contains | O(n²) | O(n) | Small arrays or learning purposes |
HashSet or Distinct() for clean and efficient duplicate removal.