Find Longest Consecutive Sequence in an Unsorted?
Array
int LongestConsecutive(int[] nums)
HashSet<int> set = new HashSet<int>(nums);
int longest = 0;
foreach (int num in set)
if (!set.Contains(num - 1))
Follow on:
int currentNum = num;
int length = 1;
while (set.Contains(currentNum + 1))
currentNum++;
length++;
longest = Math.Max(longest, length);
return longest;
Explanation:
Check only starts of sequences, count consecutive numbers using HashSet for O(n).