DEV Community

Rathod Ketan
Rathod Ketan

Posted on • Edited on

Best approach to find duplicates in an array

The question 'Find duplicate elements in an array' is frequently posed in interviews. Stay with us to verify 'whether an array contains duplicates'.

Welcome back, readers. In this blog post, I'll be elucidating how to identify similar items within an array. During interviews, this concept may be presented as 'Write an algorithm to detect duplicates in an array' or 'Find duplicate pairs in an array'. However, the approach remains consistent regardless of the phrasing."

Reverse a linked list recursively in python

for animation check video here

Program To Check An Array Contains Matching Elements

private static bool IsContainsDuplicate(int[] data)
{
    HashSet<int> list = new HashSet<int>();   

    for (int i = 0; i < data.Length; i++)
    {
        if (list.Contains(data[i]))
        {
            return true;
        }
        else
        {
            list.Add(data[i]);
        }
    }

    return false;
}
Enter fullscreen mode Exit fullscreen mode

Efficient way to find duplicates in array

In my case, during high school, I employed nested for loops to identify duplicates in an array. However, do you believe this approach is sufficient for acing an interview? I would argue not, as it lacks optimization. Therefore, stick with us to conquer the 'Efficient way to find duplicates in an array' interview question.

I'm planning to implement a HashSet to ascertain whether our array contains duplicates or not. This choice stems from the HashSet's capability to search for any element with linear time complexity and its built-in functionality to check the uniqueness of elements. For further details about HashSet, you can refer to its official site.

Find Solution of Two Sum Problem

Top comments (0)