Longest Consecutive Sequence: the idea to remember.
Find the longest run of consecutive integer values in an unsorted array, in expected linear time.
The core insight
Use a set and extend a run only when its predecessor is absent.
Why it works
Every run has exactly one smallest member. Starting only there means each distinct value is extended over at most once.
The mistake to avoid
Iterate over the set, not the original array, to avoid repeatedly expanding a duplicated start. Guard integer boundaries.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int n : nums) set.add(n);
int best = 0;
for (int n : set) {
if (n != Integer.MIN_VALUE && set.contains(n - 1)) continue;
int last = n, length = 1;
while (last != Integer.MAX_VALUE && set.contains(last + 1)) { last++; length++; }
best = Math.max(best, length);
}
return best;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.