Bhavya

Code -> Break -> Fix -> Blog

Mettl Coding Test : List the duplicate integers in the array

Leave a comment

Problem Statement

  1. Create a method which will list out the duplicate entries in a given integer array.
  2. The input array should have only positive integers.
  3. The method should take 2 parameters, 1st is the count of the array and 2nd the actual array
  4. If no duplicate entries are found then return {-1}.

Example 1 :

DuplicateArray(6, new int[] { 4, 4, 7, 8, 8, 9 });

Output={4,8}

Example 2:

DuplicateArray(6, new int[] { 4, 4, -7, 8, 8, 9 });

Output={-1}

Example 3:

DuplicateArray(7, new int[] { 3, 6, 5, 7, 8, 19, 32 });

Output={-1}

 

Soultion

public static int[] output1;

public static void DuplicateArray(int input1, int[] input2)
{
// Validate input1 as it should match with input2.count
// Validate : more than 1 integer present in the array.
// Validate : Positive integers
if (input1 != input2.Count() || input1 < 1
|| input2.FirstOrDefault(x => x < 0) < 0)
{
output1 = new int[] { -1 };
return;
}

List<int> listDuplicateValues = new List<int>();

// Group by numbers and check the count for duplicate entries.
var groups = input2.GroupBy(x => x);
foreach (var group in groups)
{
if (group.Count() > 1)
{
listDuplicateValues.Add(group.Key);
}
}

// Validate : if list is empty then set output1 to -1
output1 = listDuplicateValues.Count == 0 ?
new int[] { -1 } : output1 = listDuplicateValues.ToArray();
}

~BJS

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s