Mid From PDF Coding C# Coding Interview

Find Longest Consecutive Sequence in an Unsorted?

rray

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).

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details