public class Solution {
public int longestConsecutive(int[] num) {
HashSet<Integer> set = new HashSet<Integer>();
// Initializes the set
for(int i = 0; i < num.length; i++) {
set.add(num[i]);
}
// Expands from the middle
int max = 0;
for(int n : num) {
if(set.contains(n)) {
int len = 1;
// Expands to left
int i = n - 1;
while(set.contains(i)) {
len++;
set.remove(i);
i--;
}
// Expands to right
int j = n + 1;
while(set.contains(j)) {
len++;
set.remove(j);
j++;
}
max = Math.max(max, len);
set.remove(i);
}
}
return max;
}
}
Time: O(n)
Space: O(n)