Detect a duplicate array value
Determine whether an integer array contains any value more than once.
Course progress
Problem 62 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 = [5, 1, 8, 5]
Expected output
True
What is happening?
The final 5 has already appeared at the start of the array, so the duplicate check returns true.
Solution strategy
Build the right mental model
Insert values into a set. If an insertion fails, that value has already appeared and the array contains a duplicate.
Core concepts
arrays · hash set
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 contains-duplicate
using System;
using System.Collections.Generic;
class Program
{
static bool ContainsDuplicate(int[] numbers)
{
var seen = new HashSet<int>();
foreach (int number in numbers)
if (!seen.Add(number)) return true;
return false;
}
static void Main()
{
Console.WriteLine(ContainsDuplicate(new[] { 5, 1, 8, 5 }));
}
}Knowledge check
Questions students often ask
What is the main idea behind detect a duplicate array value?
Insert values into a set. If an insertion fails, that value has already appeared and the array contains a duplicate.
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.