Interview Question Categories

Longest Consecutive sequence of Numbers

Longest Consecutive sequence


//Longest Consecutive sequence
//Ex: If arr = {1, 5, 2, 6, 7, 9, 10, 4 }
//Longest Consecutive sequence = {4,5,6,7}
namespace longestConsecutiveSequence
{
    class Program
    {
        static int[] longestConsecutiveSequence(int[] arr)
        {
            Dictionary<int, int> table = new Dictionary<int, int>();
            int length = 0;
            int first = int.MaxValue;

            foreach (int i in arr)
            {
                //If i has already been encountered and is in table
                //then continue with next number
                if (!table.ContainsKey(i))
                {
                    int start = i;
                    int end = i;
                    //Checking if i+1 has already been encountered
                    //If so add i to the existing range in the table.
                    if (table.ContainsKey(i + 1) && table[i + 1] >= i + 1)
                    {
                        end = table[i + 1];
                        table.Remove(i + 1);
                        table.Remove(end);
                    }
                    //Checking if i-1 has already been encountered
                    //If so add i to the existing range in the table.
                    if (table.ContainsKey(i - 1) && table[i - 1] <= i - 1)
                    {
                        start = table[i - 1];
                        table.Remove(i - 1);
                        table.Remove(start);
                    }
                    //Update the table with newly found range
                    table[start] = end;
                    table[end] = start;

                    //Update the longest range found so far.
                    if (end - start + 1 > length)
                    {
                        first = start;
                        length = end - start + 1;
                    }
                }
            }

            int[] s = new int[length];
            for (int i = 0; i < length; i++) s[i] = first + i;
            return s;
        }

        static void Main(string[] args)
        {
            int[] arr = { 1, 5, 2, 6, 7, 9, 10, 4 };

            int[] longestSeq = longestConsecutiveSequence(arr);
        }
    }
}

No comments:

Post a Comment