0
0
CsharpProgramBeginner · 2 min read

C# Program to Find Duplicate Elements in Array

Use a Dictionary<int,int> to count occurrences and print elements with count greater than one, like foreach(var item in dict) if(item.Value > 1) Console.WriteLine(item.Key);.
📋

Examples

Input[1, 2, 3, 4, 5]
OutputNo duplicates found
Input[1, 2, 2, 3, 4, 4, 5]
OutputDuplicate elements: 2 4
Input[]
OutputNo duplicates found
🧠

How to Think About It

To find duplicates, go through each element and keep track of how many times it appears using a counting tool like a dictionary. Then, check which elements appear more than once and list them as duplicates.
📐

Algorithm

1
Get the input array.
2
Create an empty dictionary to store element counts.
3
For each element in the array, increase its count in the dictionary.
4
Check the dictionary for elements with count greater than one.
5
Print those elements as duplicates or print no duplicates if none found.
💻

Code

csharp
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] arr = {1, 2, 2, 3, 4, 4, 5};
        var counts = new Dictionary<int, int>();

        foreach (int num in arr) {
            if (counts.ContainsKey(num)) counts[num]++;
            else counts[num] = 1;
        }

        bool found = false;
        foreach (var item in counts) {
            if (item.Value > 1) {
                if (!found) {
                    Console.Write("Duplicate elements: ");
                    found = true;
                }
                Console.Write(item.Key + " ");
            }
        }

        if (!found) Console.WriteLine("No duplicates found");
        else Console.WriteLine();
    }
}
Output
Duplicate elements: 2 4
🔍

Dry Run

Let's trace the array [1, 2, 2, 3, 4, 4, 5] through the code

1

Initialize dictionary

counts = {}

2

Process element 1

counts = {1:1}

3

Process element 2

counts = {1:1, 2:1}

4

Process element 2 again

counts = {1:1, 2:2}

5

Process element 3

counts = {1:1, 2:2, 3:1}

6

Process element 4

counts = {1:1, 2:2, 3:1, 4:1}

7

Process element 4 again

counts = {1:1, 2:2, 3:1, 4:2}

8

Process element 5

counts = {1:1, 2:2, 3:1, 4:2, 5:1}

9

Check duplicates

Duplicates found: 2, 4

ElementDictionary State
1{1:1}
2{1:1, 2:1}
2{1:1, 2:2}
3{1:1, 2:2, 3:1}
4{1:1, 2:2, 3:1, 4:1}
4{1:1, 2:2, 3:1, 4:2}
5{1:1, 2:2, 3:1, 4:2, 5:1}
💡

Why This Works

Step 1: Counting elements

We use a Dictionary to count how many times each element appears by increasing the count each time we see the element.

Step 2: Finding duplicates

After counting, elements with counts greater than one are duplicates because they appear multiple times.

Step 3: Output duplicates

We print all elements with count more than one to show the duplicates found in the array.

🔄

Alternative Approaches

Using LINQ GroupBy
csharp
using System;
using System.Linq;

class Program {
    static void Main() {
        int[] arr = {1, 2, 2, 3, 4, 4, 5};
        var duplicates = arr.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key);
        if (duplicates.Any()) {
            Console.Write("Duplicate elements: ");
            foreach (var d in duplicates) Console.Write(d + " ");
            Console.WriteLine();
        } else {
            Console.WriteLine("No duplicates found");
        }
    }
}
This approach is concise and uses LINQ but may be less clear for beginners.
Using HashSet to track seen and duplicates
csharp
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] arr = {1, 2, 2, 3, 4, 4, 5};
        var seen = new HashSet<int>();
        var duplicates = new HashSet<int>();

        foreach (int num in arr) {
            if (!seen.Add(num)) duplicates.Add(num);
        }

        if (duplicates.Count > 0) {
            Console.Write("Duplicate elements: ");
            foreach (var d in duplicates) Console.Write(d + " ");
            Console.WriteLine();
        } else {
            Console.WriteLine("No duplicates found");
        }
    }
}
This method uses two sets to track seen and duplicate elements efficiently.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the array once, so time grows linearly with input size.

Space Complexity

Extra space is used for the dictionary to store counts, which can grow up to the size of the array.

Which Approach is Fastest?

All approaches run in linear time; using HashSet is slightly faster for just detecting duplicates without counts.

ApproachTimeSpaceBest For
Dictionary CountingO(n)O(n)Counting duplicates with frequency
LINQ GroupByO(n)O(n)Concise code with built-in methods
HashSet TrackingO(n)O(n)Fast detection of duplicates without counts
💡
Use a dictionary or hash set to count or track elements for easy duplicate detection.
⚠️
Beginners often forget to check if an element is already counted and print duplicates multiple times.