1. class Solution {
  2. /**
  3.   1. Store all elements in a HashSet, This allows O(1) lookup for checking if a number exists.
  4.   2. Only start building a sequence from numbers that are the beginning
  5.   - number is the start if, set does not contains (element-1)
  6.   - count (currentLength) how long the sequence goes, so Expand forward (ele + 1, ele + 2, …)
  7.   - once you found the current length of sequence, Track the maximum length
  8.   3. repeat step-2 for all the array elements
  9.   4. return the max length
  10.   */
  11. public int longestConsecutive(int[] nums) {
  12. if(nums.length == 0)
  13. return 0;
  14.  
  15. // to remove duplicates
  16. HashSet<Integer> set = new HashSet<>();
  17. for(int ele : nums)
  18. set.add(ele);
  19.  
  20. int maxLength = 0;
  21. for(int ele : nums)
  22. {
  23. // find the start of sequence
  24. if(set.contains(ele - 1) == false) // this is not the start
  25. {
  26. int length = 1;
  27. while(set.contains(ele + 1))
  28. {
  29. ele++;
  30. length++;
  31. }
  32. maxLength = Math.max(length, maxLength);
  33. }
  34. }
  35. return maxLength;
  36. }
  37. }