Saturday, 26 May 2018

Find Consecutive Elements in Unsorted Array in O(n) - C++ Code



#include<iostream>
#include<set>

int findConsecutiveElements(int arr[], int n)
{
        std::set<int> s;
        int ans = 0;

        for (int i = 0; i < n; i++)
                s.insert(arr[i]);

        for (int i=0; i<n; i++)
        {
                if (s.find(arr[i]-1) == s.end())
                {
                        int j = arr[i];
                        while (s.find(j) != s.end())
                                j++;

                        ans = std::max(ans, j - arr[i]);
                }
        }
        return ans;
}

int main()
{
        int arr[] = {1,21, 24, 25, 9, 3, 11, 4, 20, 22,23};
        int n = sizeof arr/ sizeof arr[0];
        std::cout << "Length of the Longest consecutive elements is "
                << findConsecutiveElements(arr, n);
        return 0;
}