Problem Statement
Which approach efficiently finds the longest consecutive elements sequence in an unsorted array of integers?
Explanation
Using a hash set you can check for each number whether it is a sequence start (num‐1 absent) then count forwards. This yields O(n) average time. Sorting would take O(n log n).
Code Solution
SolutionRead Only
Set<Integer> s = new HashSet<>(Arrays.asList(nums)); int longest=0; for(int n:nums){ if(!s.contains(n-1)){ int cur=n; while(s.contains(cur)) cur++; longest = Math.max(longest, cur-n); } }