...

/

Solution: Find Duplicates in an Array with No Repetition

Solution: Find Duplicates in an Array with No Repetition

Explore various approaches to solving the challenge of efficiently finding duplicates in an array.

Solution 1: Brute force

using System;
class Program
{
/// <summary>
/// Method to find duplicates in a given array.
/// </summary>
/// <param name="arr">An array of integers.</param>
/// <returns>An array of duplicate integers with no repetition.</returns>
public static int[] FindDuplicates(int[] arr)
{
int[] result = new int[arr.Length]; // An array to store duplicates
int resultIndex = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++) // Starting from i + 1
{
if (arr[i] == arr[j])
{
bool alreadyExists = false;
for (int k = 0; k < resultIndex; k++)
{
if (result[k] == arr[i])
{
alreadyExists = true;
break;
}
}
if (!alreadyExists)
{
result[resultIndex] = arr[i];
resultIndex++;
}
}
}
}
int[] finalResult = new int[resultIndex];
Array.Copy(result, finalResult, resultIndex); // Copy to a new array with correct size
return finalResult;
}
// Driver to test above code
static void Main()
{
int[] arr = { 1, 2, 5, 1, 4, 2, 1, 1 };
int[] result = FindDuplicates(arr);
Console.WriteLine("[" + string.Join(", ", result) + "]");
}
}

Explanation

The solution takes one element from the array, compares it with every other element (starting from i + 1), and checks if they both are equal. If they are, it adds it to the resultant array if the number is not present already.

Time complexity

The array is iterated once for each element present, so the time complexity is in O( ...