Remove duplicate values
Remove duplicate integers from an array while keeping the first occurrence of each value in its original order.
Course progress
Problem 29 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [4, 2, 4, 1, 2, 3]
Expected output
4 2 1 3
What is happening?
Keep each value only on its first appearance. The second 4 and second 2 are skipped, preserving the order 4, 2, 1, 3.
Solution strategy
Build the right mental model
A HashSet records which values have appeared. Append a value to the result only when Add reports that it is new.
Core concepts
hash set · stable order
Complexity
Average time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for remove-duplicates
using System;
using System.Collections.Generic;
class Program
{
static int[] DistinctInOrder(int[] numbers)
{
var seen = new HashSet<int>();
var result = new List<int>();
foreach (int number in numbers)
if (seen.Add(number)) result.Add(number);
return result.ToArray();
}
static void Main()
{
Console.WriteLine(string.Join(" ", DistinctInOrder(new[] { 4, 2, 4, 1, 2, 3 })));
}
}Knowledge check
Questions students often ask
What is the main idea behind remove duplicate values?
A HashSet records which values have appeared. Append a value to the result only when Add reports that it is new.
What is the time and space complexity of this solution?
Average time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.