Home > Mobile >  Find out the missing element from an unsorted integer array in C#
Find out the missing element from an unsorted integer array in C#

Time:08-08

I have a unsorted integer array, Find the missing value from the array by using only array length. For more details below.

int[] array = new int[] { 3, 4, 5, 7, 8, 2, 1 };

Another input is Minimum is 1 and Maximum is 8. I want to get the output is 6.

CodePudding user response:

This could be variable based on what goes into your array. Is there supposed to be 8 entries but only 1 missing every time? will all entries be incrementally the same i.e 1,2,3 or 2,4,6 etc.

If so sort the array and add an increment variable so you can iterate the array returning on the first failure:

private int FindMissingInt()
{
    int[] array = new int[] { 3, 4, 5, 7, 8, 2, 1 };

    Array.Sort(array);

    int increment = 1;

    for (int i = 0; i < array.Length; i  )
    {
        if ((i   1) * increment != array[i])
        {
            return (i   1) * increment;
        }
    }
    return 0;
}

This works for this case, may not work for others.

CodePudding user response:

Here is a language extension to assist with obtaining missing elements.

public static class SequenceExtensions
{
    public static int[] Missing(this int[] sequence)
    {
        Array.Sort(sequence);
        return Enumerable.Range(sequence.First(), sequence.Last()).Except(sequence)
            .ToArray();
    }
}

Use it

partial class Program
{
    static void Main(string[] args)
    {

        int[] array = { 3, 4, 5, 7, 8, 2, 1 };
        var output = array.Missing();
        Console.WriteLine(string.Join(",", output));

    }
}
  • Related