How to check if array contains a duplicate number using C#?

Checking if an array contains duplicate numbers is a common programming task in C#. There are multiple approaches to solve this problem, ranging from simple loops to LINQ methods and hash-based techniques.

Using Dictionary to Count Occurrences

The dictionary approach counts the frequency of each element in the array. Any element with a count greater than 1 is a duplicate −

using System;
using System.Collections.Generic;

namespace Demo {
    public class Program {
        public static void Main(string[] args) {
            int[] arr = {87, 55, 23, 87, 45, 23, 98};
            var dict = new Dictionary<int, int>();
            
            foreach(var num in arr) {
                if (dict.ContainsKey(num))
                    dict[num]++;
                else
                    dict[num] = 1;
            }
            
            Console.WriteLine("Number occurrences:");
            bool hasDuplicates = false;
            foreach(var val in dict) {
                Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
                if (val.Value > 1) hasDuplicates = true;
            }
            
            Console.WriteLine("\nArray contains duplicates: " + hasDuplicates);
        }
    }
}

The output of the above code is −

Number occurrences:
87 occurred 2 times
55 occurred 1 times
23 occurred 2 times
45 occurred 1 times
98 occurred 1 times

Array contains duplicates: True

Using HashSet for Efficient Duplicate Detection

A HashSet provides a more efficient way to check for duplicates by attempting to add each element. If an element already exists, Add() returns false −

using System;
using System.Collections.Generic;

namespace Demo {
    public class Program {
        public static void Main(string[] args) {
            int[] arr = {87, 55, 23, 87, 45, 23, 98};
            var hashSet = new HashSet<int>();
            
            bool hasDuplicates = false;
            foreach(int num in arr) {
                if (!hashSet.Add(num)) {
                    Console.WriteLine("Duplicate found: " + num);
                    hasDuplicates = true;
                }
            }
            
            Console.WriteLine("Array contains duplicates: " + hasDuplicates);
        }
    }
}

The output of the above code is −

Duplicate found: 87
Duplicate found: 23
Array contains duplicates: True

Using LINQ GroupBy Method

LINQ provides a concise way to group elements by their value and identify duplicates −

using System;
using System.Linq;

namespace Demo {
    public class Program {
        public static void Main(string[] args) {
            int[] arr = {87, 55, 23, 87, 45, 23, 98};
            
            var duplicates = arr.GroupBy(x => x)
                               .Where(group => group.Count() > 1)
                               .Select(group => group.Key);
            
            Console.WriteLine("Duplicate numbers:");
            foreach(var duplicate in duplicates) {
                Console.WriteLine(duplicate);
            }
            
            bool hasDuplicates = duplicates.Any();
            Console.WriteLine("\nArray contains duplicates: " + hasDuplicates);
        }
    }
}

The output of the above code is −

Duplicate numbers:
87
23

Array contains duplicates: True

Comparison of Methods

Method Time Complexity Space Complexity Best For
Dictionary O(n) O(n) Counting occurrences
HashSet O(n) O(n) Early duplicate detection
LINQ GroupBy O(n) O(n) Functional programming style

Conclusion

There are multiple efficient ways to check for duplicates in an array using C#. The HashSet approach is most efficient for simple duplicate detection, while the Dictionary method is best when you need to count occurrences. LINQ provides a concise, readable solution for functional programming enthusiasts.

Updated on: 2026-03-17T07:04:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements